w3resource logo


Python Exercises

Python Challenges: Check whether a given number is an ugly number

Python Challenges - 1: Exercise-24 with Solution

Write a Python program to check whether a given number is an ugly number.

Input : 12
Output : True

Ugly numbers are positive numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...
shows the first 10 ugly numbers.
Note: 1 is typically treated as an ugly number.

Explanation :

Python: Ugly number

Sample Solution :-

Python Code :

def is_ugly(num):
        if num == 0:
            return False
        for i in [2, 3, 5]:
            while num % i == 0:
                num /= i
        return num == 1

print(is_ugly(12))
print(is_ugly(13))

Output :

True                                                                    
False 

Flowchart:

Python Flowchart: Check whether a given number is an ugly number

Python Code Editor:

def is_ugly(num):
        if num == 0:
            return False
        for i in [2, 3, 5]:
            while num % i == 0:
                num /= i
        return num == 1

print(is_ugly(12))
print(is_ugly(13))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program