Javascript Prime Number generator
Ever wanted to create a prime number generator? You can make a really basic one with Javascript, or use this approach to create one in a different programming language. Here’s the basic code:
//list of all prime numbers
var primes = [2];
//current number
var current = 1;
//function to generate primes
var getPrimes = function(){
//add 2 since even numbers are never prime
current += 2;
for(var i = 0; i < primes.length; i++){
//cycle through generated prime numbers and check if the current number is divisible by any of them
if( current % primes[i] === 0){
//number is divisible by a prime number
return;
}
}
//add the prime number to the array
primes.push(current);
}
//set interval to keep generating prime numbers
window.setInterval(getPrimes, 1);
To view the generated prime numbers, open the Developer Console
in your web browser (press ctrl+shift+i
for chrome), type in primes
and press enter.
That’s it! Go crack some codes