Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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)

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top