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 × 3ugly number
  • 8 = 23ugly number
  • 14 = 2 × 7not 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
Ugly Number Detection: Remove Allowed FactorsInputn = 302×3×5÷ 230 ÷ 2 = 1515 ÷ 2 = 15(no more 2s)÷ 315 ÷ 3 = 55 ÷ 3 = 5(no more 3s)÷ 55 ÷ 5 = 11 ÷ 5 = 1(no more 5s)Result: 1UGLY ✓All factors removedCounter-example: n = 14 (Not Ugly)14 ÷ 2 = 77 ÷ 3 = 77 ÷ 5 = 7Result: 7NOT UGLY ✗7 is forbidden factor💡 Key InsightInstead of finding all prime factors, systematically remove allowed factorsIf only 1 remains, the number contained only allowed prime factors (2, 3, 5)Time: O(log n) | Space: O(1)
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

n
2n
Linearithmic
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
Linear Space

Constraints

  • -231 ≤ n ≤ 231 - 1
  • n must be checked for positive values only
  • Consider edge cases like 0, 1, and negative numbers
Asked in
Amazon 25 Google 18 Microsoft 15 Apple 12
28.4K Views
Medium Frequency
~15 min Avg. Time
985 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen