【发布时间】:2014-04-02 07:12:09
【问题描述】:
感谢阅读。对 Javascript 和一般编程来说相当陌生。
我正在寻找一种方法来返回给定数字的最大素数。我的第一个直觉是使用 while 循环进行计数并找到数字的素因子,将因子存储在数组中并在每次找到时重置。这样,数组中的最后一项应该是最大的素数。
var primerizer = function(input){
var factors = [];
var numStorage = input
for (x=2; numStorage != 1; x++){ // counter stops when the divisor is equal to the last number in the
// array, meaning the input has been fully factorized
if (result === 0) { // check if the number is prime; if it is not prime
factors.push(x); // add the divisor to the array of prime numbers
numStorage = numStorage/x // divide the number being calculated by the divisor
x=2 // reset the divisor to 2 and continue
};
};
primeFactor = factors.pop();
return primeFactor;
}
document.write(primerizer(50))
这仅返回 2、未定义或什么都不返回。我担心 for 循环的停止条件必须根据与开始条件相同的变量来定义,所以我尝试使用 while 循环来代替。
var primerizer = function(input){
var factors = [];
var numStorage = input
x=2
while (numStorage != 1){
var result = numStorage%x;
if (result === 0) {
factors.push(x);
numStorage = numStorage/x
x=2
}
else {
x = x+1
}
}
return factors.pop();
}
document.write(primerizer(50)
同样的问题。也许我忽略了我的语法有问题?非常感谢任何意见。
谢谢。
【问题讨论】: