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



Suppose we have a number n, we have to check whether its prime factors only include 2, 3 or 5 or not.

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

To solve this, we will follow these steps −

  • if n < 0, then
    • return False
  • factor := a list with elements [2,3,5]
  • for each i in factor, do
    • while n mod i is same as 0, do
      • n := n / i
  • return true when n is same as 1, otherwise false

Let us see the following implementation to get better understanding −

Example

 Live Demo

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

Input

18

Output

True
Updated on: 2020-10-05T07:48:51+05:30

899 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements