Sponsored
Sponsored
This approach involves dividing the number by its prime factors (2, 3, and 5) as long as it is divisible by them. If after removing all these factors, the number reduces to 1, it is an ugly number; otherwise, it is not.
Time Complexity: O(log n).
Space Complexity: O(1).
1def is_ugly(n: int) -> bool:
2 if n <= 0:
3 return False
4 for p in [2, 3, 5]:
5 while n % p == 0:
6 n //= p
7 return n == 1
This Python solution divides the number n by 2, 3, and 5 iteratively until n reduces to 1, confirming it to be an ugly number.
This alternative approach involves using recursion to systematically divide the number by 2, 3, and 5. By tracing back all divisions reaching 1, this method can also verify the ugliness of a number.
Time Complexity: O(log n).
Space Complexity: O(log n), due to recursion stack.
1public class
This Java solution uses a helper method to recursively determine ugly numbers by factor division and end-state evaluation (equaling 1).