Ugly Number

Problem

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

Solution

public class Solution {
    public boolean isUgly(int num) {
        if (num <= 0) return false;
        for (int i = 2; i < 6; i++) {
            while (num % i == 0) num /= i;
        }
        return num == 1;
    }
}

Analysis

Since ugly number is positive, we first check whether the given input is non-negative
Then we divide 2, 3, 4, 5 if it's divisible
At the end, we just return if given input is equal to 1
If it is ugly number, it must have left with factor 1 only
Because 7 is another prime factor, 8 can be divisible 2 and 4, same as 9 and so on

results matching ""

    No results matching ""