Magicsheet logo

Ugly Number

Easy
36.3%
Updated 6/1/2025

Ugly Number

What is this problem about?

The Ugly Number interview question introduces the concept of numbers whose only prime factors are 2, 3, and 5. By definition, 1 is also considered an ugly number. Given an integer, your task is to determine whether it fits this criteria. This problem requires you to repeatedly decompose a number by its allowed factors until you reach a conclusion.

Why is this asked in interviews?

This problem is a favorite among top-tier companies like Apple, Meta, and Google because it tests basic Math interview patterns and recursive or iterative logic. It evaluates how a candidate handles number theory concepts without requiring advanced mathematical knowledge. It also reveals whether a candidate can write clean, efficient loops to handle repeated division.

Algorithmic pattern used

The core Math interview pattern for this problem is repeated division. You take the input number and continuously divide it by 2 as long as it's divisible. You then repeat this process for 3 and then for 5. If, after all these divisions, the remaining value is 1, the original number was "ugly." If the remainder is anything else (or if the number was non-positive to begin with), it is not an ugly number.

Example explanation

Let's check if 14 is an ugly number.

  1. Is 14 divisible by 2? Yes. 14/2=714 / 2 = 7.
  2. Is 7 divisible by 2? No.
  3. Is 7 divisible by 3? No.
  4. Is 7 divisible by 5? No.
  5. The remaining number is 7. Since 7 is not 1, 14 is NOT an ugly number. Now check 12:
  6. 12/2=612 / 2 = 6.
  7. 6/2=36 / 2 = 3.
  8. Is 3 divisible by 2? No.
  9. 3/3=13 / 3 = 1.
  10. The remaining number is 1. Therefore, 12 IS an ugly number.

Common mistakes candidates make

One major mistake is not handling non-positive numbers (like 0 or negative integers), which cannot be ugly numbers. Another is trying to find all prime factors first, which is much less efficient than simply dividing by 2, 3, and 5. Candidates also sometimes forget that the starting point of 1 is a special case that must return true.

Interview preparation tip

For Math interview questions, always consider the simplest iterative reduction first. You don't always need a complex data structure to solve a number theory problem. Focus on the base cases and ensure your loops terminate correctly for edge cases like 0 or 1.

Similar Questions