-1

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?!

Ivan Vrzogic
  • 157
  • 1
  • 8
  • Do you really need prime number check? Sounds like you can check first condition and on any other number return false: `return n%2 === 0 || n%3 === 3 || n%5 === 0` – Justinas Feb 01 '21 at 12:20
  • `-4` is a hamming number according to your implementation. I don't think it is, however. – Wiktor Zychla Feb 01 '21 at 12:24
  • I would have to add condition that n have to be positive (n>0). Thank you! – Ivan Vrzogic Feb 01 '21 at 12:26
  • I would have to add check if a number is prime number greater than or equal to 7, because all other factors are contained within condition that n has to be divisible by either 2, or 3 or 5, and must not be divisible by any prime number greater than 5. – Ivan Vrzogic Feb 01 '21 at 12:28
  • 1
    @IvanVrzogic [Hamming numbers](https://en.wikipedia.org/wiki/Regular_number) take the form of `2^i * 3^j * 5^k` where `i,j,k >= 0`. So the last bullet point in @guidot's answer would be the correct solution. – 001 Feb 01 '21 at 13:01
  • function isHamming(n){ for(var i=0;i – Ivan Vrzogic Feb 01 '21 at 23:04

1 Answers1

0
  • 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.
guidot
  • 5,095
  • 2
  • 25
  • 37
  • The point is that a number to be eligible to be called Hamming number must be divisible by 2, or 3 or 5, AND at the same time must NOT be divisible with any prime number greater than or equal to 7. So don't see how to exclude prime numbers check from the code. – Ivan Vrzogic Feb 01 '21 at 12:42