Javascript 汉明码不起作用
我试图得到前10个汉明数(素数为2、3和5的数)。第一个Javascript 汉明码不起作用,javascript,Javascript,我试图得到前10个汉明数(素数为2、3和5的数)。第一个getFactors(num)函数返回我想要的结果(一个set素数因子),但是第二个hammingNum()函数没有按需要运行。有什么想法吗 let factors = [] isPrime = true function getFactors(num){ while (num % 2 === 0){ factors.push(2);
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()
let factors=[]
isPrime=true
函数getFactors(num){
而(数值%2==0){
因素:推动(2);
num/=2;
}
对于(i=3;i 对于第二个示例中的(i=1;i,您正在将2&&3&&5==5
传递到has
方法中
这个怎么样
var s = getFactors(i);
if(s.has(2) && s.has(3) && s.has(5)) {
...
该行是问题的原因:
if ((getFactors (i)).has (2 && 3 && 5)) {/* ... */}
您必须明确列出每个条件:
if (getFactors(i).has(2) && getFactors(i).has(3) && getFactors(i).has(5)) {/* ... */}
由于getFactors
似乎是一个潜在的昂贵调用,您应该只执行一次,然后存储结果并使用:
const factors = getFactors(i);
if (factors.has(2) && factors.has(3) && factors.has(5)) {/* ... */}
最后,您可以使用array稍微缩短该条件(如果需要)。every
方法:
const factors = getFactors(i);
if ([2, 3, 5].every(n => factors.has(n))) {/* ... */}
2&&3&&5
应该做什么?逻辑并返回5
。感谢您的提示。我根据您的建议调整了代码(不包括缩短版本),但当我运行它时,它被卡在一个无限循环上。你知道为什么吗?我猜你的getFactors
函数也不正常工作。我怀疑它总是返回一个空集,这意味着没有任何东西被推入列表
数组,这意味着list.length<11
总是正确的(如此无限循环).GetgetFactors
函数工作正常,它返回一组基本因子。