Call a number ugly when it is positive and the only primes that divide it are 2, 3 and 5. The number 1 counts as ugly, since no prime divides it at all.
Given an integer n, return true if it is ugly and false otherwise.
Example 1
Input: n = 60 Output: true Why: 60 = 2 · 2 · 3 · 5
2 more examples and the constraints
Example 2
Input: n = 0 Output: false Why: zero is not positive
Example 3
Input: n = 21 Output: false Why: 21 = 3 · 7, and 7 is not allowed
Constraints
- −2,147,483,648 ≤ n ≤ 2,147,483,647 (any 32-bit integer)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Factor it fullyO(√n)
- Strip 2, 3 and 5O(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n near 2,147,483,647 | Verdict |
|---|---|---|---|
| Factor it fully | O(√n) | Passes; more work than needed | |
| Strip 2, 3 and 5 | O(log n) | Best; a few dozen divisions |
n = the number being tested.
Edge cases to test
- n = 0. Not positive, so false. Without the check, dividing out 2s loops forever.
- Negative n. −30 has only 2, 3 and 5 in it, but ugly numbers must be positive: false.
- n = 1. No prime factors at all, so it is ugly: true.
- A large prime. 2,147,483,647 is prime. Nothing divides out, n stays above 1: false.
Common mistakes
- Forgetting the n ≤ 0 check, so 0 loops forever and negatives give wrong answers.
- Dividing by each prime only once, so 60 is left as 2 instead of 1.
- Returning false for n = 1 because it has no 2, 3 or 5 in it.
How to talk through it
- 1Clarify. Is 1 ugly? What about 0 and negative numbers?
- 2Start general. Factor n by trial division and check every prime factor; it is O(√n).
- 3Turn it around. We only care whether a prime other than 2, 3, 5 exists, so strip those three and see what is left.
- 4Code the loop. Check n ≤ 0 first, then divide by 2, 3 and 5 while each one fits, and compare n with 1.
- 5Test out loud. Run 0, 1, a negative number and a number with a 7 in it.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?