w3resource

JavaScript: Check a given number is an ugly number or not

JavaScript Math: Exercise-100 with Solution

Check Ugly Number

Write a JavaScript program to check if a given number is ugly.

Ugly numbers are positive numbers whose only prime factors are 2, 3 or 5. The first 10 ugly numbers are:
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...
Note: 1 is typically treated as an ugly number.

Visual Presentation:

JavaScript Math: Check a given number is an ugly number or not.

Test Data:
(12) -> true
(18) -> true
(19) -> false

Sample Solution:

JavaScript Code:

/**
 * Function to check if a number is an ugly number.
 * @param {number} n - The number to check.
 * @returns {boolean} - Returns true if the number is an ugly number, otherwise false.
 */
function test(n) {
  map = [5, 3, 2]; // Array of prime factors that define an ugly number
  for (let i = 0; i < map.length && n > 1; i++) { // Iterate through the prime factors array
    while (n % map[i] === 0) n /= map[i]; // Divide the number by the current prime factor if it's divisible by it
  }
  return n === 1; // If the number becomes 1 after dividing by all prime factors, it's an ugly number
};  

// Test cases
n = 12;
console.log("n = " +n);
console.log("Check the said number is an ugly number? "+test(n));

n = 18;
console.log("Original text: " +n);
console.log("Check the said number is an ugly number? "+test(n));

n = 19;
console.log("Original text: " +n);
console.log("Check the said number is an ugly number? "+test(n));

Output:

n = 12
Check the said number is an ugly number? true
Original text: 18
Check the said number is an ugly number? true
Original text: 19
Check the said number is an ugly number? false

Flowchart:

JavaScript: Add digits until there is only one digit.

Live Demo:


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that checks if a number is ugly by repeatedly dividing it by 2, 3, and 5 until it equals 1.
  • Write a JavaScript function that iterates through the prime factors 2, 3, and 5 to determine if a number is ugly.
  • Write a JavaScript function that validates input and handles cases where the number is zero or negative when checking for ugliness.
  • Write a JavaScript function that returns a boolean indicating if the number is ugly and logs intermediate division steps.

Go to:


PREV : Sum Digits Until One Digit.
NEXT : Find nth Ugly Number.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.