w3resource

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

JavaScript Math: Exercise-100 with Solution

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:

See the Pen javascript-math-exercise-100 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Check a given number is an ugly number or not.
Next: Find the nth ugly number.

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.