Program to check a number is ugly number or not in Python

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. In other words, an ugly number can be expressed as 2i × 3j × 5k where i, j, and k are non-negative integers.

So, if the input is like n = 18, then the output will be True, as 18's prime factors are 2 and 3 (18 = 2 × 32).

Algorithm

To solve this, we will follow these steps ?

  • If n ? 0, then return False (ugly numbers are positive)
  • Create a list of factors [2, 3, 5]
  • For each factor i in [2, 3, 5], do:
    • While n is divisible by i, divide n by i
  • Return True if n becomes 1, otherwise False

Implementation

class Solution:
    def solve(self, n):
        if n <= 0:
            return False
        
        factors = [2, 3, 5]
        for factor in factors:
            while n % factor == 0:
                n //= factor
        
        return n == 1

# Test the solution
ob = Solution()
print("Is 18 an ugly number?", ob.solve(18))
print("Is 14 an ugly number?", ob.solve(14))
print("Is 1 an ugly number?", ob.solve(1))

The output of the above code is ?

Is 18 an ugly number? True
Is 14 an ugly number? False
Is 1 an ugly number? True

How It Works

Let's trace through the algorithm with n = 18:

  • Initially n = 18
  • Divide by 2: 18 ÷ 2 = 9, so n = 9
  • 9 is not divisible by 2, move to next factor
  • Divide by 3: 9 ÷ 3 = 3, so n = 3
  • Divide by 3: 3 ÷ 3 = 1, so n = 1
  • 1 is not divisible by 5
  • Since n = 1, return True

Alternative Implementation

Here's a more concise version using a simple function ?

def is_ugly_number(n):
    if n <= 0:
        return False
    
    # Remove all factors of 2, 3, and 5
    for factor in [2, 3, 5]:
        while n % factor == 0:
            n //= factor
    
    # If n becomes 1, it's an ugly number
    return n == 1

# Test with different numbers
test_numbers = [1, 6, 8, 14, 18, 30]
for num in test_numbers:
    print(f"{num}: {is_ugly_number(num)}")

The output of the above code is ?

1: True
6: True
8: True
14: False
30: True

Conclusion

An ugly number contains only 2, 3, and 5 as prime factors. The algorithm repeatedly divides by these factors until either n becomes 1 (ugly number) or contains other prime factors (not ugly).

Updated on: 2026-03-25T10:37:58+05:30

954 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements