使用Javascript找到最大的素数因子

时间:2014-04-02 07:12:09

标签: 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))

这只返回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)

同样的问题。也许我的语法存在问题,我忽略了?任何意见都非常感谢。

谢谢。

6 个答案:

答案 0 :(得分: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)

答案 1 :(得分:2)

你可以试试这个

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]);

或者:(此解决方案使用更多内存)

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);

答案 2 :(得分:0)

  <script>
        function LPrimeFactor() {
            var x = 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(x(50));
        }
    </script>

 <input type="button" onclick="LPrimeFactor();" />

Here是我尝试使用您的代码的示例

答案 3 :(得分:0)

这是我使用的解决方案应该在理论上工作的解决方案......除了一个小问题。在某个大小的数字(您可以在代码中更改),它会使浏览器太忙而崩溃。

https://github.com/gordondavidescu/project-euler/blob/master/problem%203%20(Javascript)

添加内联代码:

<p id="demo">

</p>

<script>
function isPrime(value) {
    for(var i = 2; i < value; i++) {
        if(value % i === 0) {
            return false;
        }
    }
    return value > 1;
}


function biggestPrime(){
    var biggest = 1;
    for(var i = 600851470000; i < 600851475143; i++){
    if (isPrime(i) != false)
      {
      biggest = i;
      }
     document.getElementById("demo").innerHTML = biggest;
    }
   }

biggestPrime();

</script>

</p>

答案 4 :(得分:0)

<script>
//Finds largest prime factor

find = 2165415  ;  // Number to test!

var prime = 0;
loop1:
for (i = 2; i < find; i++){
prime = 0;
if (find%i == 0){
  document.write(find/i);
  for (j = 2; j < (find / i); j++){
  if ((find / i )%j == 0){
    document.write(" divides by "+j+"<br>");
    prime = prime + 1;
    break;
  }
}
if (prime == 0){
    document.write("<br>",find/i, "- Largest Prime Factor")
    prime = 1;
    break;
  }
 }
}
if (prime==0)
  document.write("No prime factors ",find," is prime!")

答案 5 :(得分:0)

这是我自己的解决方案。

//function
function largestPrimeFactor (num) {

    //initialize the variable that will represent the divider
    let i = 2;

    //initialize the variable that will represent the quotient
    let numQuot = num;

    //array that will keep all the dividers
    let primeFactors = [];

    //execute until the quotient is equal to 1
        while(numQuot != 1) {

    /*check if the division between the number and the divider has no reminder, if yes then do the division keeping the quotient in numQuot, the divider in primeFactors and proceed to restart the divider to 2, if not then increment i by one an check again the condition.*/
            if(numQuot % i == 0){
                numQuot /= i;
                primeFactors.push(i);
                i = 2;
            } else {
                i++;
            }
        }

    /*initialize the variable that will represent the biggest prime factor. biggest is equal to the last position of the array, that is the biggest prime factor (we have to subtract 1 of .length in order to obtain the index of the last item)*/
    let biggest = primeFactors[primeFactors.length - 1];

    //write the resutl
    console.log(biggest);
}

//calling the function
largestPrimeFactor(100);