Ugly Number
To solve this coding challenge, we need to determine if a given positive integer \( n \) is an "ugly number." An ugly number is defined as a positive integer whose prime factors are limited to 2, 3, and 5. Therefore, any number that has only these prime factors (or is 1) will be considered ugly.
Explanation:
- Understanding the Problem : First, we need to reduce any integer \( n \) by its prime factors (2, 3, and 5) iteratively. If after completely dividing \( n \) by these factors the result is 1, then \( n \) is an ugly number.
-
Special Case Handling
: Any integer less than or equal to 0 cannot be an ugly number because an ugly number is defined as a positive integer. Hence, we can immediately return
False
- Iterative Division :
- Continuously divide \( n \) by 2 as long as \( n \) is divisible by 2.
- Repeat the same process for 3 and 5.
-
Finally, check if the resultant \( n \) is 1. If it is, then \( n \) consists only of the prime factors 2, 3, and 5. Otherwise, it has other prime factors, and we should return
False
- Initialization and Edge Case Check :
-
If \( n \) is less than or equal to 0, return
False
- Divide by Prime Factors :
- While \( n \) is divisible by 2, divide \( n \) by 2.
- While \( n \) is divisible by 3, divide \( n \) by 3.
- While \( n \) is divisible by 5, divide \( n \) by 5.
- Final Check :
-
After all divisions, if \( n \) is equal to 1, return
True
-
Otherwise, return
False
Detailed Steps in Pseudocode:
Pseudocode:
// Function to check if the number is ugly
function isUglyNumber(n):
// Step 1: Handle edge case
if n <= 0:
return False
// Step 2: Process all prime factors 2, 3, and 5
while n % 2 == 0:
n = n / 2
while n % 3 == 0:
n = n / 3
while n % 5 == 0:
n = n / 5
// Step 3: Final check
if n == 1:
return True
else:
return False
Clarification and Additional Details:
-
The problem constraints specify that \( n \) can be an integer from \( -2^{31} \) to \( 2^{31} - 1 \). Since the problem specifies an "ugly number" as a positive integer, the function immediately returns
False
- By continuously dividing \( n \) by 2, 3, and 5, we systematically remove these prime factors. If no other factors remain (i.e., \( n \) becomes 1), we confirm \( n \) could only be made up of these primes, validating its "ugliness".