1

all! recently i've been trying to build a mercende prime number producer/generator, using the lucas lehmer method of testing. the code works for the first 4 numbers, and then fails for the rest. any suggestions? thanks!

var totalPrimes = Math.floor(prompt("What would you like the upper limit of 
                                     our search for primes to be?"));
for (var i = 2; i < totalPrimes; i++) {
    var lucasNum = 4;
    var curNumber = (Math.pow(2, (i+1))-1);
    for (var x = 0; i-1 > x; x++) {
        if (lucasNum / curNumber > 1) {
            lucasNum = (Math.pow(lucasNum, 2)-2);
        } else {
            lucasNum = (Math.pow(lucasNum, 2)-2);
        }
    }
    if (lucasNum % curNumber === 0) {
        console.log("The number " + curNumber + " is prime");
    } else {
        console.log("The number " + curNumber + " is not prime");
    }
}
4castle
  • 32,613
  • 11
  • 69
  • 106
A. Eglin
  • 11
  • 4

1 Answers1

0

The mantissa (or significand) of a Javascript number is 53-bit wide. Therefore, the biggest integer that can be stored in full precision is:

2^53 - 1 = 9007199254740991 = Number.MAX_SAFE_INTEGER

(You may want to read this page for more details.)

Your algorithm is likely to hit this limit very quickly. The precision explosion occurs within this statement:

lucasNum = (Math.pow(lucasNum, 2)-2);

which is included in a loop.

Arnauld
  • 5,847
  • 2
  • 15
  • 32