Ugly Number

Easymath
Category: Fundamentals

Approach

Ugly Number

Approach

Divide by 2, 3, 5 until no longer divisible.

Algorithm

  1. Handle edge case: n ≤ 0 returns false
  2. For each factor (2, 3, 5):
    • While n divisible by factor: divide
  3. Return true if n becomes 1

Complexity

  • Time: O(log n) - divisions reduce n
  • Space: O(1) - constant space

Key Insights

  • Ugly number has only 2, 3, 5 as prime factors
  • Repeatedly dividing removes these factors
  • If result is 1, no other prime factors exist

Solution

java
1class Solution {
2    public boolean isUgly(int n) {
3        if (n <= 0) return false;
4        
5        for (int factor : new int[]{2, 3, 5}) {
6            while (n % factor == 0) {
7                n /= factor;
8            }
9        }
10        
11        return n == 1;
12    }
13}
Loading visualizer...