Ugly Number using Python

Ugly numbers are the numbers whose prime factors are limited to 2, 3, and 5. Finding the Ugly number is a popular question in coding interviews. Here you need to check if a number is an ugly number or not. So, if you want to know how to solve this problem using Python, this article is for you. In this article, I will take you through how to solve the ugly number problem using Python.

Ugly Number using Python

In the ugly number problem, you will be given an integer. You need to check if 2, 3, and 5 are the only prime factors of the integer or not. If 2, 3, and 5 are the only prime factors of the input integer, then the integer is an ugly number, and your output should return true, otherwise, return false. Below is an example of the input and output of this problem:

Input: 6
Output: True (2×3 = 6)

I hope you have understood what ugly numbers are. Now, below is how you can solve this problem using the Python programming language:

def isUgly(n):
    if n > 0:
        factors = [2, 3, 5]
        for i in factors:
            while n % i == 0:
                n = n // i
        return n == 1
    else:
        return 0

print(isUgly(6))
Output: True

So this is how you can solve the ugly number problem using Python. You can find many more practice questions for coding interviews solved and explained using Python here.

Summary

In the ugly number problem, you will be given an integer. You need to check if 2, 3, and 5 are the only prime factors of the integer or not. I hope you liked this article on how to solve the ugly number problem using Python. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

Coder with the ♥️ of a Writer || Data Scientist | Solopreneur | Founder

Articles: 1334

Leave a Reply