Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Prime Number Generation With ES6 Generators

| Comments

Well, there are many effective prime number generation alogrithms out there, but I got lazy and tried something like:

primes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function isPrime(n) {
   if (isNaN(n) || !isFinite(n) || n%1 || n<2) return false;
   var m = Math.sqrt(n);
   for (var i=2;i<=m;i++) if (n%i==0) return false;
   return true;
}

function *genPrime() {
   var count = 0;
   while(1) {
    if(isPrime(count)) yield count;
    count++;
   }
}

Now, keep generating them!

1
2
3
4
var meh = genPrime();
while(1) {
 console.log(meh.next().value);
}

BTW one more intresting read

Comments