- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- while n mod i is same as 0, do
- return true when n is same as 1, otherwise false
Let us see the following implementation to get better understanding −
Example
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
Advertisements