1. Brute Force — Test Each Integer Sequentially
Intuition
Increment a counter from 1 upward. For each number, divide out 2, 3, and 5 as much as possible. If the remainder is 1, it is ugly. Stop when count reaches n.
When to apply: Only for understanding the problem definition (times out for n > 50).
Algorithm
- Step 1: Define isUgly(num): divide num by 2, 3, 5 while divisible. Return num == 1.
- Step 2: Loop num = 1, 2, 3 ...
- Step 3: If isUgly(num), count++.
- Step 4: When count == n, return num.
#include <iostream>using namespace std; class Solution { bool isUgly(int num) { if (num <= 0) return false; while (num % 2 == 0) num /= 2; while (num % 3 == 0) num /= 3; while (num % 5 == 0) num /= 5; return num == 1; } public: int nthUglyNumber(int n) { int count = 0; int num = 0; while (count < n) { num++; if (isUgly(num)) { count++; } } return num; }}; int main() { Solution sol; cout << "10th Ugly Number (Brute Force): " << sol.nthUglyNumber(10) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(U_n)— O(U_n) exponential runtime. - Space complexity:
O(1)— O(1) auxiliary space.
Why Brute Force Doesn't Scale:
Testing sequentially takes 2 billion operations for n = 1690. Three Pointers DP takes exactly 1690 operations (1,000,000x faster).
Three Pointers DP computes the 1690th ugly number in ~0.05ms.