An ugly number is a positive integer which does not have a prime factor other than 2, 3, and 5.
Given an integer n, return true if n is an ugly number.
Example 1:
Input: n = 6 Output: true Explanation: 6 = 2 × 3
Example 2:
Input: n = 1 Output: true Explanation: 1 has no prime factors.
Example 3:
Input: n = 14 Output: false Explanation: 14 is not ugly since it includes the prime factor 7.
Constraints:
-231 <= n <= 231 - 1When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you need to check if a specific number only has allowed prime factors, meaning it is an ugly number. The brute force strategy is to repeatedly shrink the number by dividing it by those allowed factors as much as possible to see what is left over at the end.
Here's how the algorithm would work step-by-step:
def is_ugly(target_number):
# Numbers less than or equal to zero cannot be ugly since factors require positivity
if target_number <= 0:
return False
allowed_factors = [2, 3, 5]
# Continuously divide by allowed factors to strip out all valid prime components
for current_factor in allowed_factors:
while target_number % current_factor == 0:
target_number //= current_factor
# If the remaining value is reduced to one, all prime factors were valid ugly factors
return target_number == 1To determine if a number is ugly, the optimal approach repeatedly divides the number by its allowed prime factors as long as it can evenly do so. If the process successfully strips away all those specific factors and reaches the number one, then the original number was indeed ugly.
Here's how the algorithm would work step-by-step:
def is_ugly(input_number):
# Zero and negative numbers cannot be ugly by definition.
if input_number <= 0:
return False
current_value = input_number
# Repeatedly divide by allowed prime factors to strip them out.
for prime_factor in [2, 3, 5]:
while current_value % prime_factor == 0:
current_value //= prime_factor
# If the remaining value is one, all prime factors were allowed.
return current_value == 1| Case | How to Handle |
|---|---|
| Input n is less than or equal to zero | Return false immediately since ugly numbers are strictly positive integers. |
| Input n is exactly 1 | Return true because 1 has no prime factors and vacuously meets the condition. |
| Input n is a prime number other than 2, 3, or 5 | The division loops will leave n greater than 1, causing the algorithm to return false. |
| Input n is a large valid ugly number containing large powers of 2, 3, or 5 | Successive division loops reduce n efficiently without risking integer overflow or recursion depth limits. |
| Input n is a large non-ugly number with prime factors like 7 or 11 | The algorithm exhausts factors 2, 3, and 5, leaving n > 1 after the loops and correctly returns false. |