How to determine if given number is Hamming number by combining two functions in JavaScript?

350 views Asked by At

The goal is to determine if a number is Hamming number?! As we know Hamming number is a number that contains only 2, 3 and 5 as factors. That means that a number must not contain any prime number greater than 5! So I created a function isPrimeNumber that determines if a number is prime, and thereafter I created function that determines if a number contains factors 2, 3 and 5?!

function isPrimeNumber(n){
    if(n===1){
        return true;
    }else if((n%1!==0)||(n<=0)){
        return false;
    }else{
    for (var i=2; i<n; i++){
        if (n%i===0)
            return false;
        }
        return true;
    }
}

function isHamming(n){
    if(((n%2===0)||(n%3===0)||(n%5===0))){
        return true;
    }else if((isPrimeNumber(n)===true)&&(n>=7)){
        return false;
    }else{
        return false;
    }
}

Would like to combine those two functions to determine if a number entered is Hamming number or not?!

1

There are 1 answers

1
guidot On
  • The prime number check does not contribute something useful and has a horrible time complexity O(n) in the given implementation.
  • It is not sufficient, to show that the number is a multiple of 2, 3 or 5. One has additionally to show, that no other factor is contained. (Example: 14 is no prime, contains factor 2 but also 7 -> no Hamming number)
  • I see no alternative to the following: you have to divide sucessively by 2, 3 and 5 (each factor as long as it is contained) and then look, whether you arrive at 1.