JavaScript: Show the Hamming numbers

JavaScript Math: Exercise-44 with Solution

Write a JavaScript function to show the first twenty Hamming numbers. Hamming numbers are numbers with prime factors of 2, 3 and 5

Sample Solution:-

HTML Code:

<!DOCTYPE html>
  <meta charset="utf-8">
  <title>JavaScript function to show the Hamming numbers</title>


JavaScript Code:

function Hamming(n) {
        var succession = [1];
        var length = succession.length;
        var candidate = 2;
        while (length < n) {
            if (isHammingNumber(candidate)) {
                succession[length] = candidate;
        return succession;
 function isHammingNumber(num) {
        while (num % 5 === 0) num /= 5;
        while (num % 3 === 0) num /= 3;
        while (num % 2 === 0) num /= 2;

        return num == 1;


Sample Output:


Pictorial Presentation:

JavaScript: Math - Show the Hamming numbers.


Flowchart: JavaScript Math - Show the hamming numbers number

Live Demo:

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

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to get all prime numbers from 0 to a specified number
Next: Write a JavaScript function to subtract elements from one another in an array.

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.