Ugly Number

Easy

Topics
Math

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return true if n is ugly.

Example 1

631null
Divide out every factor of 2, then 3, then 5. What is left is 1, so the answer is true — a number is ugly exactly when nothing but 1 remains.
Each node is the value after dividing out one factor of 2, 3 or 5.
Input:  n = 6
Output: true

Example 2

147null
Input:  n = 14
Output: false

Example 3

1null
Input:  n = 1
Output: true

Constraints

  • -2^31 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

An ugly number has no prime factors beyond 2, 3 and 5. So divide those three out as far as they go; if what remains is 1, nothing else was ever there. If anything else remains, it is a factor outside the allowed set — possibly prime, possibly composite, but either way disqualifying.

The order of the divisions does not matter, because removing factors is commutative. The positivity guard does: zero and negatives are not ugly, and 0 % 2 == 0 would otherwise loop forever.

Approach

  1. Reject n <= 0.
  2. For each of 2, 3, 5: divide while divisible.
  3. Return whether 1 remains.

Dry Run

n = 6     /2 -> 3, /3 -> 1          1 remains  -> true
n = 8     /2 -> 4 -> 2 -> 1          -> true
n = 14    /2 -> 7; 7 not divisible by 3 or 5
          7 remains  -> false   (7 is the offending factor)
n = 1     no divisions apply, 1 == 1 -> true
n = 0     guard -> false
n = -6    guard -> false

Complexity

  • Time — O(log n): every division at least halves the number, so the total iteration count across all three loops is bounded by log base 2 of n.
  • Space — O(1).

Common Pitfalls

  • Omitting the positivity guard. Zero divides by 2 forever.
  • Forgetting that 1 is ugly — it has no prime factors at all, so it qualifies vacuously.
  • Testing only whether n is divisible by 2, 3 or 5, rather than dividing them out completely. 14 is divisible by 2 and is still not ugly.
  • Trying to factorise n fully. Only these three primes matter; whatever is left over needs no identification.

Full Solution — all languages

class Solution:
    def isUgly(self, n):
        if n <= 0:
            return False
        for p in (2, 3, 5):
            while n % p == 0:
                n //= p
        return n == 1
SensAI
Beta
Tap the mic to stop voice mode