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

110 views Asked by At

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!

4

There are 4 answers

0
Namysh On BEST ANSWER

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`);
}

0
marcos On

You can use Array.filter with Array.every, for example:

const output = factors.filter(factor => [2,3,5].every(num => num !== factor))
0
Peter B On

You can use .some(), or more precisely !f.some(x => x > 5) or in text: true if no factors are found that are > 5.

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

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

for (var num = 30; num <= 40; num++) {
  var f = getAllFactorsFor(num);
  console.log(num + " has factors: " + f.toString() + ". Hamming number: " + !f.some(x => x > 5))
}

0
Ivan Vrzogic On

I've combined different suggestions and googled also and came to my solution version for check up if entered number is Hamming number or not:

The code:

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

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

    return factors;
}

function isHamming(remainder){
    if(getAllFactorsFor(remainder).every(f => [2, 3, 5].includes(f))){
        return true;
    }else{
        return false;
    }
}