简体   繁体   English

如何通过结合 JavaScript 中的两个函数来确定给定数是否为汉明数?

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

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?目标是确定一个数字是否是汉明数?众所周知,汉明数是一个仅包含 2. 3 和 5 作为因子的数字,这意味着一个数字不能包含任何大于 5 的素数,所以我创建了确定数字是否为素数的 function isPrimeNumber? and thereafter I created function that determines if a number contains factors 2, 3 and 5?!然后我创建了 function 来确定一个数字是否包含因子 2、3 和 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?!想结合这两个函数来确定输入的数字是否是汉明数?!

  • The prime number check does not contribute something useful and has a horrible time complexity O(n) in the given implementation.在给定的实现中,素数检查没有贡献任何有用的东西并且具有可怕的时间复杂度 O(n)。
  • 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.仅仅证明这个数字是 2、3 或 5 的倍数是不够的。还必须证明不包含其他因素。 (Example: 14 is no prime, contains factor 2 but also 7 -> no Hamming number) (示例:14 不是素数,包含因数 2 但也包含 7 -> 没有汉明数)
  • 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.我认为没有其他选择:您必须依次除以 2、3 和 5(只要包含每个因子),然后查看是否达到 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM