Implement the isUglyNumber method that checks whether the number has only 2, 3, and 5 as prime factors.

The input contains an integer n. Your task is to check whether it is an ugly number.

An ugly number is a positive number whose only prime factors are 2, 3, and 5. The number 1 is usually treated as ugly because it has no other prime factors.

Example 1

Input
n (int) = 6
Returns (boolean) true

Example 2

Input
n (int) = 1
Returns (boolean) true

Example 3

Input
n (int) = 14
Returns (boolean) false

Repeatedly divide the number by 2, 3, and 5 whenever possible.

If the number becomes 1, then all of its prime factors were only from the allowed set. If any other value remains, it has another prime factor and is not ugly.

Numbers less than or equal to 0 are not ugly.

Pseudocode:

function isUglyNumber(n):
    if n <= 0:
        return false
    for factor in [2, 3, 5]:
        while n % factor == 0:
            n = n / factor
    return n == 1
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.