simple underscore.js projects, walk through, & tutorial

findNextPrime(), computing prime numbers


Basic Prime Number Generator:

function findNextPrime(x){

   
    // no test conditions, hardwired
    if (x < 0){return 0;}
    if (x < 1){return 1;}
    if (x < 2){return 2;}
    if (x < 3){return 3;}
   
    var isPrime = true;
   
    var divisor = 2;
   
    // This is the maximum divisor value that needs to be checked
    // As any higher divisor will be matched by some lower one
    // which would have already been checked for
    var maxDivisor = Math.floor(Math.sqrt(x) + 2);
   
    x = Math.floor(x);
   
    var nextTest = x + 1;
   
    while (divisor <= maxDivisor){
   
        if (nextTest%divisor === 0){
        isPrime = false;
        }
       
        divisor += 1;
       
    }  // if nextTest / divisor then it's not a prime
   
    if (isPrime === true){
        return nextTest;
    } else {
        return findNextPrime(nextTest);
    } // interator that feed findNextPrime into itself
   
}  // end findNextPrime();


document.getElementById('outputOne').innerHTML = findNextPrime(9);

Output:
Nada Yet


Find the the ten smallest prime numbers:

outputTwo[0] = 0;
for (i = 1; i <= 10; i++){
    outputTwo[i] = findNextPrime(outputTwo[i - 1]);
}

Output:
Nada Yet



A Web Search indicated these where the three smallest six digit prime numbers:
100003, 100019, 100043, 100049

So for a final test, let's see if those numbers are what the program kicks out:

outputThree = findNextPrime(100000) + ', ' + findNextPrime(100004) + ', ' + findNextPrime(100020) + ', ' + findNextPrime(100045);

Output:
Nada Yet




_.moreUnderscoreProjects

© Copyright 2013 Brett Paufler