使用Javascript找到最大的素数因子 [英] Find the largest prime factor with Javascript

查看:63
本文介绍了使用Javascript找到最大的素数因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢阅读。对于Javascript和一般编程来说都是新手。

Thanks for reading. Pretty new to Javascript and programming in general.

我正在寻找一种方法来返回给定数字的最大素数因子。我的第一直觉是使用while循环来计算并查找数字的素数因子,将因子存储在数组中并在每次找到时重置。这样,数组中的最后一项应该是最大的素数因子。

I'm looking for a way to return the largest prime factor of a given number. My first instinct was to work with a while loop that counts up and finds prime factors of the number, storing the factors in an array and resetting each time it finds one. This way the last item in the array should be the largest prime factor.

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循环。

This only returned 2, undefined, or nothing. My concern was that the stop condition for the for loop must be defined in terms of the same variable as the start condition, so I tried it with a while loop instead.

 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)

同样的问题。也许我忽略了我的语法问题?非常感谢任何输入。

Same problem. Maybe there's a problem with my syntax that I'm overlooking? Any input is much appreciated.

谢谢。

推荐答案

你可以试试这个

var x = 1, div = 0, primes = [];

while(primes.length != 10001) {
    x++;
    for(var i = 2; i < x && !div; i++) if(!(x % i)) div++;
    if(!div) primes.push(x); else div = 0;
}

console.log(primes[primes.length-1]);

或者:(此解决方案使用更多你的记忆)

or this: (This solution uses more of your memory)

var dont = [], max = 2000000, primes = [];

for (var i = 2; i <= max; i++) {
    if (!dont[i]) {
        primes.push(i);
        for (var j = i; j <= max; j += i) dont[j] = true;
    }
}

console.log(primes);

这篇关于使用Javascript找到最大的素数因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆