Taro Logo

Ugly Number

#244 Most AskedEasy
Topics:
Bit ManipulationGreedy Algorithms

An ugly number is a positive integer which does not have a prime factor other than 2, 3, and 5.

Given an integer n, return true if n is an ugly number.

Example 1:

Input: n = 6
Output: true
Explanation: 6 = 2 × 3

Example 2:

Input: n = 1
Output: true
Explanation: 1 has no prime factors.

Example 3:

Input: n = 14
Output: false
Explanation: 14 is not ugly since it includes the prime factor 7.

Constraints:

  • -231 <= n <= 231 - 1

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of the integer `n` that we can expect as input?
  2. How should the function handle non-positive integers, such as zero or negative numbers, since the problem states ugly numbers are positive integers?
  3. Is `1` considered an ugly number since its prime factors are limited to 2, 3, and 5 (vacuously true)?
  4. Are there any specific time or space complexity constraints I should adhere to beyond the standard optimal approach?
  5. Should the function return a boolean value (`true` or `false`), or is there any expected custom output format?

Brute Force Solution

Approach

Imagine you need to check if a specific number only has allowed prime factors, meaning it is an ugly number. The brute force strategy is to repeatedly shrink the number by dividing it by those allowed factors as much as possible to see what is left over at the end.

Here's how the algorithm would work step-by-step:

  1. Take the starting number and check if it is divisible by the first allowed factor.
  2. If it is, divide the number by that factor and repeat the division process with the new result.
  3. If the number cannot be divided evenly by that factor anymore, move on to the second allowed factor and repeat the division process.
  4. Then, move on to the third allowed factor and do the same thing, dividing as many times as possible.
  5. Keep going through this entire sequence of allowed factors over and over again until the number cannot be divided by any of them any further.
  6. Finally, look at the leftover number to see if it has been reduced all the way down to one.
  7. If the leftover number is one, then the original number is successfully identified as an ugly number; otherwise, it is not.

Code Implementation

def is_ugly(target_number):
    # Numbers less than or equal to zero cannot be ugly since factors require positivity
    if target_number <= 0:
        return False

    allowed_factors = [2, 3, 5]

    # Continuously divide by allowed factors to strip out all valid prime components
    for current_factor in allowed_factors:
        while target_number % current_factor == 0:
            target_number //= current_factor

    # If the remaining value is reduced to one, all prime factors were valid ugly factors
    return target_number == 1

Big(O) Analysis

Time Complexity
O(log n) – The input size is the number n itself, and the cost is driven by the repeated division of n by its prime factors 2, 3, and 5. In the worst-case scenario where n is a power of 2, 3, or 5, we divide the number continuously until it reaches 1. The number of divisions required is proportional to the logarithm of n in base 2, 3, or 5, since the value decreases multiplicatively. Therefore, the total operations scale logarithmically with the input size, simplifying to O(log n).
Space Complexity
O(1) – The algorithm only uses a few primitive scalar variables to hold the current number and loop states during the division process. As the input integer increases in magnitude, the number of required variables remains constant. No dynamic data structures, hash maps, or recursive call stacks are utilized. Consequently, the auxiliary memory footprint stays entirely fixed regardless of the input size, resulting in a constant space complexity.

Optimal Solution

Approach

To determine if a number is ugly, the optimal approach repeatedly divides the number by its allowed prime factors as long as it can evenly do so. If the process successfully strips away all those specific factors and reaches the number one, then the original number was indeed ugly.

Here's how the algorithm would work step-by-step:

  1. Check if the number is zero or negative, because such numbers cannot be ugly.
  2. Check if the number is already equal to one, which means it is successfully reduced and therefore considered ugly.
  3. Check if the number can be divided evenly by two without leaving any remainder, and if so, update the number by performing that division.
  4. Check if the number can be divided evenly by three without leaving any remainder, and if so, update the number by performing that division.
  5. Check if the number can be divided evenly by five without leaving any remainder, and if so, update the number by performing that division.
  6. Repeat the division process continuously until the number can no longer be divided evenly by any of those three allowed factors.
  7. After all possible divisions are complete, look at the final remaining value to see if it ended up as one; if it did, the original number is ugly, and if it did not, it is not ugly.

Code Implementation

def is_ugly(input_number):
    # Zero and negative numbers cannot be ugly by definition.
    if input_number <= 0:
        return False

    current_value = input_number

    # Repeatedly divide by allowed prime factors to strip them out.
    for prime_factor in [2, 3, 5]:
        while current_value % prime_factor == 0:
            current_value //= prime_factor

    # If the remaining value is one, all prime factors were allowed.
    return current_value == 1

Big(O) Analysis

Time Complexity
O(log n) – The time complexity is driven by the repeated division of the input number n by its allowed prime factors 2, 3, and 5. In the worst-case scenario, n is a power of 2, 3, or 5, meaning the number will be divided successively until it reaches 1. Since the value of n decreases exponentially with each successful division operation, the number of steps required is proportional to the logarithm of n base 2, 3, or 5. Therefore, the operations scale logarithmically with the input size, simplifying the total time complexity to O(log n).
Space Complexity
O(1) – The algorithm relies entirely on a few primitive integer variables to store the changing number as it undergoes repeated divisions. There are no dynamic data structures, hash maps, or recursive call stacks allocated during the execution. Because the amount of extra memory remains constant regardless of the magnitude of the input integer N, the auxiliary space complexity is strictly O(1).

Edge Cases

Input n is less than or equal to zero
How to Handle:
Return false immediately since ugly numbers are strictly positive integers.
Input n is exactly 1
How to Handle:
Return true because 1 has no prime factors and vacuously meets the condition.
Input n is a prime number other than 2, 3, or 5
How to Handle:
The division loops will leave n greater than 1, causing the algorithm to return false.
Input n is a large valid ugly number containing large powers of 2, 3, or 5
How to Handle:
Successive division loops reduce n efficiently without risking integer overflow or recursion depth limits.
Input n is a large non-ugly number with prime factors like 7 or 11
How to Handle:
The algorithm exhausts factors 2, 3, and 5, leaving n > 1 after the loops and correctly returns false.
0/245 completed