class Solution:
def isUgly(self, n: int) -> bool:
if n <= 0:
return False
for p in [2, 3, 5]:
while n % p == 0:
n //= p
return n == 1
class Solution {
public:
bool isUgly(int n) {
if (n <= 0) return false;
for (int p : {2, 3, 5}) {
while (n % p == 0) {
n /= p;
}
}
return n == 1;
}
};
class Solution {
public boolean isUgly(int n) {
if (n <= 0) return false;
int[] primes = {2, 3, 5};
for (int p : primes) {
while (n % p == 0) {
n /= p;
}
}
return n == 1;
}
}
var isUgly = function(n) {
if (n <= 0) return false;
const primes = [2, 3, 5];
for (let p of primes) {
while (n % p === 0) {
n /= p;
}
}
return n === 1;
};
The Ugly Number problem asks you to determine whether a given integer n
is an "ugly number." A number is considered ugly if its only prime factors are 2, 3, or 5. In other words, after repeatedly dividing n
by 2, 3, and 5 (as many times as possible), you should end up with 1 if n
is ugly.
n
is less than or equal to 0, it is not considered ugly.n
.
At first glance, you might think you need to check all possible prime factors of n
. However, the problem specifically restricts ugly numbers to those whose only prime factors are 2, 3, or 5. This means that any other prime factor (like 7 or 11) immediately disqualifies n
from being ugly.
The brute-force approach would be to factorize n
and check if any prime factors other than 2, 3, or 5 exist. But we can optimize by simply dividing n
by 2, then by 3, then by 5, as many times as possible. If after all these divisions we're left with 1, then n
had no other prime factors.
This approach is both simple and efficient, as we only care about three divisors and don't need to generate or check all primes.
Here’s a step-by-step breakdown of the algorithm:
n
is less than or equal to zero, immediately return False
. Ugly numbers must be positive.
n
is divisible by the current prime, divide n
by that prime.n
equals 1, then it is ugly (since it only had 2, 3, and 5 as factors). Otherwise, it is not ugly.
We use a simple loop for each of the three primes, which is efficient and easy to understand. This approach avoids the need for complex factorization logic or prime generation.
Let’s walk through an example with n = 30
:
n = 30
.n
is 1, so 30 is an ugly number.
Another example, n = 14
:
n = 14
.n
and checking all possible divisors up to sqrt(n
) would take O(sqrt(n)) time.
The Ugly Number problem is elegantly solved by repeatedly dividing the input by 2, 3, and 5. If the result is 1, it’s ugly; otherwise, it’s not. This approach is efficient, easy to implement, and leverages the problem’s constraints for a straightforward solution.