jmk*_*oll 2 javascript factorization
谢谢阅读.一般来说,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))
Run Code Online (Sandbox Code Playgroud)
这只返回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)
Run Code Online (Sandbox Code Playgroud)
同样的问题.也许我的语法存在问题,我忽略了?任何输入都非常感谢.
谢谢.
小智 7
我找到的最短答案是:
function largestPrimeFactor(n){
var i=2;
while (i<=n){
if (n%i == 0){
n/=i;
}else{
i++;
}
}
console.log(i);
}
var a = **TYPE YOUR NUMBER HERE**;
largestPrimeFactor(a)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7961 次 |
| 最近记录: |