Javascript Prime Number generator

Written by Max Pelic on

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:

1//list of all prime numbers

2
var primes = ;
3//current number
4
var current = 1;
5//function to generate primes
6
var getPrimes = function(){
7 //add 2 since even numbers are never prime
8
current += 2;
9 for(var i = 0; i < primes.length; i++){
10 //cycle through generated prime numbers and check if the current number is divisible by any of them
11
if( current % primes[i] === 0){
12 //number is divisible by a prime number
13
return;
14 }
15 }
16 //add the prime number to the array
17
primes.push(current);
18}
19
20//set interval to keep generating prime numbers
21
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