#263

Ugly Number

Easy Prime factors

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

An ugly number is a positive integer whose only prime factors are 2, 3 and 5. Decide whether n is ugly.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: is n built only from the primes 2, 3 and 5?

Why this works: divide out every 2, 3 and 5. If nothing else was in there, 1 is left.

Example: n = 14

14 / 2 = 77 not divisible by 2, 3, 5left with 7 ≠ 1 → not ugly

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting n <= 0; the while loop on 0 never ends because 0 % 2 == 0.