Find the largest prime factor with Javascript

jmknoll picture jmknoll · Apr 2, 2014 · Viewed 11.9k times · Source

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.

Answer

Austin picture Austin · Mar 18, 2015

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)