Find the largest prime factor with Javascript

半城伤御伤魂 提交于 2019-12-21 23:16:06

问题


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

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

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.

Thank you.


回答1:


You can try with this

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



回答2:


The shortest answer I've found is this:

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)



回答3:


here is my own solution.

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



回答4:


  <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 is an example i tried with your code




回答5:


Here is the solution I used that should work in theory... except for one small problem. At a certain size number (which you can change in the code) it crashes the browser due to making it too busy.

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

Adding the code inline:

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



回答6:


<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!")



来源:https://stackoverflow.com/questions/22804017/find-the-largest-prime-factor-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!