首页 > 解决方案 > 汉明数字代码不起作用

问题描述

我试图获得前 10 个汉明数(素数为 2、3 和 5 的数字)。第一个getFactors(num)函数返回我想要的(set主要因素之一),但是第二个hammingNum()函数没有按预期运行。有任何想法吗?

    let factors = []
        isPrime = true


    function getFactors(num){   

        while (num % 2 === 0){
            factors.push(2);
            num /= 2;
        } 

        for (i = 3; i < num; i++){
            if (num % i === 0){
                isPrime = false;
                break;
            } else {
                isPrime = true
            }
        } 

        if (isPrime){
            factors.push (num)
        }

        if (!isPrime) {
            factors.push (i)
            getFactors (num/i)
        }

        return new Set (factors) //return a set of prime numbers     
    } 


    function hammingNums(){
        let list = []

        while (list.length < 11){
            for (i = 1; i<1000; i++){

                if ((getFactors (i)).has (2 && 3 && 5)){
                    list.push (i)
                } 
            } 
        } return list

    hammingNums()

标签: javascript

解决方案


在第二个示例中,您将传递2 && 3 && 5 === 5给该has方法。

这个怎么样?

var s = getFactors(i);
if(s.has(2) && s.has(3) && s.has(5)) {
    ...

推荐阅读