javascriptarraysanyhamming-numbers

# How to find if any element within an array is different than 2, 3 and 5 in JavaScript?

The goal is to determine whether a number input is a Hamming number?! Hamming numbers are all numbers that factorized contain just prime numbers 2, 3 and 5. If a number factorized contains any number different than either of 2, 3 and 5 is NOT Hamming number. So I found how to factorize each number input, and factors formed an array. I would like to set up condition whether any factor is different than 2, 3 or 5 to be able to exclude that numbers from potential list of Hamming numbers!

The code that factorize each number to prime factors is:

``````function getAllFactorsFor(remainder) {
var factors = [], i;

for (i = 2; i <= remainder; i++) {
while ((remainder % i) === 0) {
factors.push(i);
remainder /= i;
}
}

return factors;
}
``````

Now I need to set up condition to exclude all numbers from this newly formed array that contain any prime factors different than 2, 3 and 5!

Solution

• You can use `every` order to check that all desired factors are present :

``````function getAllFactorsFor(remainder) {
var factors = [], i;

for (i = 2; i <= remainder; i++) {
while ((remainder % i) === 0) {
factors.push(i);
remainder /= i;
}
}

return factors;
}

for(let i = 0; i < 20; i++) {
if(getAllFactorsFor(i).every(f => [2, 3, 5].includes(f)))
console.log(`\${i} is a Hamming number`);
else
console.log(`\${i} is not a Hamming number`);
}``````