Ugly Number - Problem
An ugly number is a positive integer whose only prime factors are 2, 3, and 5. In other words, it can be expressed as 2i × 3j × 5k where i, j, and k are non-negative integers.
Given an integer n, return true if n is an ugly number, otherwise return false.
Examples:
6 = 2 × 3→ ugly number ✅8 = 23→ ugly number ✅14 = 2 × 7→ not ugly (contains prime factor 7) ❌
Note: By definition, 1 is considered an ugly number since it has no prime factors.
Input & Output
example_1.py — Basic Ugly Number
$
Input:
n = 6
›
Output:
true
💡 Note:
6 = 2 × 3, which only contains the prime factors 2 and 3. Therefore, 6 is an ugly number.
example_2.py — Single Prime Factor
$
Input:
n = 8
›
Output:
true
💡 Note:
8 = 2³, which only contains the prime factor 2. Therefore, 8 is an ugly number.
example_3.py — Non-Ugly Number
$
Input:
n = 14
›
Output:
false
💡 Note:
14 = 2 × 7. Since 7 is a prime factor other than 2, 3, or 5, 14 is not an ugly number.
Visualization
Tap to expand
Understanding the Visualization
1
Start with number n
Begin with the input number to test
2
Remove all 2s
Divide by 2 repeatedly while possible
3
Remove all 3s
Divide by 3 repeatedly while possible
4
Remove all 5s
Divide by 5 repeatedly while possible
5
Check remainder
If 1 remains, number was ugly; otherwise not ugly
Key Takeaway
🎯 Key Insight: Rather than finding all prime factors, systematically eliminate allowed factors (2, 3, 5). If 1 remains, the original number was ugly!
Time & Space Complexity
Time Complexity
O(log n)
We divide n by 2, 3, or 5 repeatedly. In worst case, we do this log n times
⚡ Linearithmic
Space Complexity
O(1)
Only using constant extra space for variables
✓ Linear Space
Constraints
- -231 ≤ n ≤ 231 - 1
- n must be checked for positive values only
- Consider edge cases like 0, 1, and negative numbers
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code