Check for Ugly number in JavaScript

In the decimal number system, ugly numbers are positive integers whose only prime factors are 2, 3, or 5. This means an ugly number can be expressed as 2i × 3j × 5k where i, j, and k are non-negative integers.

For example, the integers 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 are all ugly numbers because they only contain the prime factors 2, 3, and 5. However, 7, 11, 13, 14 are not ugly numbers as they contain other prime factors.

Algorithm

To check if a number is ugly, we repeatedly divide it by 2, 3, and 5 as long as it's divisible by these factors. If we eventually reach 1, the number is ugly. If we're left with any other value, it means there are other prime factors present.

Example

const num = 274;

const isUgly = num => {
    // Handle edge cases
    if (num <= 0) return false;
    if (num === 1) return true;
    
    while (num !== 1) {
        if (num % 2 === 0) {
            num /= 2;
        } else if (num % 3 === 0) {
            num /= 3;
        } else if (num % 5 === 0) {
            num /= 5;
        } else {
            return false;
        }
    }
    return true;
};

console.log(isUgly(num));    // 274 = 2 × 137, contains prime factor 137
console.log(isUgly(60));     // 60 = 2² × 3 × 5, only contains 2, 3, 5
console.log(isUgly(140));    // 140 = 2² × 5 × 7, contains prime factor 7
console.log(isUgly(1));      // 1 is considered ugly by definition
console.log(isUgly(30));     // 30 = 2 × 3 × 5, only contains 2, 3, 5

Output

false
true
false
true
true

How It Works

The function works by repeatedly dividing the input number by 2, 3, and 5:

  • 274: 274 ÷ 2 = 137. Since 137 is not divisible by 2, 3, or 5, it returns false
  • 60: 60 ÷ 2 = 30, 30 ÷ 2 = 15, 15 ÷ 3 = 5, 5 ÷ 5 = 1. Returns true
  • 140: 140 ÷ 2 = 70, 70 ÷ 2 = 35, 35 ÷ 5 = 7. Since 7 is not divisible by 2, 3, or 5, it returns false

Alternative Implementation

function isUglyNumber(n) {
    if (n <= 0) return false;
    
    // Remove all factors of 2, 3, and 5
    const factors = [2, 3, 5];
    for (let factor of factors) {
        while (n % factor === 0) {
            n /= factor;
        }
    }
    
    return n === 1;
}

// Test with various numbers
const testNumbers = [1, 6, 8, 14, 30];
testNumbers.forEach(num => {
    console.log(`${num} is ${isUglyNumber(num) ? 'ugly' : 'not ugly'}`);
});

Output

1 is ugly
6 is ugly
8 is ugly
14 is not ugly
30 is ugly

Conclusion

An ugly number contains only the prime factors 2, 3, and 5. The algorithm repeatedly divides by these factors until either reaching 1 (ugly) or finding an indivisible remainder (not ugly).

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements