You might have heard about natural numbers, prime numbers, even numbers, and odd numbers. But, have you ever wondered what an ugly number is? In this article, we will discuss what an ugly number is. We will also write a program to check for an ugly number in python.
What Is An Ugly Number?
A number is said to be an ugly number if it has only 2,3, and 5 as its prime factors. In other words, If a number can be obtained by multiplying powers for 2, 3, or 5, the number is said to be an ugly number.
For instance, 18 can be obtained as 21x 32. Hence, it is an ugly number. Similarly, 90 is also an ugly number as it can be obtained as 21x 32x 51. On the contrary, 126 is not an ugly number as it can be obtained as 21x 32x 71. Here, 126 has 7 as one of its prime factors. Hence, it is not an ugly number.
Now, let us formulate an algorithm to check for an ugly number in Python.
Algorithm To Check For Ugly Number In Python
To check if a number is an ugly number or not, we will perform repetitive division on it. First, we will divide the given number repeatedly with 2. If the resultant number becomes indivisible by 2, we will check if the number is 1 or not. If it’s 1, we will say that a number is an ugly number. Otherwise, we will perform repetitive division on the resultant by 3. Once the resultant becomes indivisible by 3, we will check if it’s 1 or not. If yes, we will say that the given number is an ugly number. Otherwise, we will perform repetitive division on the resultant by 5. Once the resultant becomes indivisible by 5, we will check if the resultant is 1. If yes, we will say that a number is an ugly number. Otherwise, we will say that the number is not an ugly number.
Let us now implement this idea in Python
Python Program To Check For Ugly Number
Here, we have implemented a function is_ugly() using the while loop for repetitive division and if-else statements for condition checking. The function takes an integer as an input argument and returns True if the input number is an ugly number. Otherwise, it returns False.
def is_ugly(N):
while N % 2 == 0:
N = N // 2
if N == 1:
return True
while N % 3 == 0:
N = N // 3
if N == 1:
return True
while N % 5 == 0:
N = N // 5
if N == 1:
return True
return False
input_number = 18
output = is_ugly(input_number)
print("{} is an ugly number:{}".format(input_number, output))
input_number = 126
output = is_ugly(input_number)
print("{} is an ugly number:{}".format(input_number, output))
Output:
18 is an ugly number:True
126 is an ugly number:False
Conclusion
In this article, we have discussed and implemented a program to check whether a given number is an ugly number or not. To learn more about numbers in python, you can read this article on decimal numbers in python. You might also like this article on complex numbers in python.
The post Check For Ugly Number In Python appeared first on PythonForBeginners.com.
from Planet Python
via read more
No comments:
Post a Comment