Problem Description
Given an integer n, determine whether it is an ugly number. An ugly number is a positive integer that only has prime factors 2, 3, and 5. The number 1 is considered ugly because it has no prime factors.
Key Insights
- If n is not positive, it cannot be an ugly number.
- Continuously divide n by 2, 3, and 5 to factor out valid prime factors.
- If after removing all factors 2, 3, and 5, n becomes 1, then n is an ugly number.
- If n is not 1 after removal, then n contains other prime factors hence is not ugly.
Space and Time Complexity
Time Complexity: O(log n) since the number is divided by constant factors. Space Complexity: O(1) constant extra space.
Solution
The solution involves an iterative division process. We repeatedly divide the number by 2, 3, and 5 if it is divisible by any of them. The idea is that if n is composed solely of these factors, then after continuous division, n should reduce to 1. If n is reduced to any number other than 1, it means there are other prime factors involved, and the number is not ugly. This approach uses only basic arithmetic operations and conditional checks, which makes it efficient in terms of both time and space.