-
-
Save boris-spas/bb550d091575c0c682c799961e27fcd6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Naive prime calculator | |
function isPrime(x) { | |
for (i = 2; i < x; i++) { | |
if (x % i == 0) { | |
return false | |
} | |
} | |
return true | |
} | |
function findPrime(i) { | |
prime = i; | |
do { | |
prime = prime + 1; | |
if (isPrime(prime)) { | |
return prime; | |
} | |
} while (true); | |
} | |
// Prime number calculator based on the Sieve of Eratosthenes algorithm. | |
class AcceptFilter { | |
accept(n) { | |
return true | |
} | |
} | |
class DivisibleByFilter { | |
constructor(number, next) { | |
this.number = number; | |
this.next = next; | |
} | |
accept(n) { | |
var filter = this; | |
// if (filter != null) { | |
while (filter != null) { | |
if (n % filter.number === 0) { | |
return false; | |
} | |
// return filter.next.accept(n); | |
filter = filter.next; | |
} | |
return true; | |
} | |
} | |
class Primes { | |
constructor() { | |
this.number = 2; | |
this.filter = new AcceptFilter(); | |
} | |
next() { | |
while (!this.filter.accept(this.number)) { | |
this.number++; | |
} | |
this.filter = new DivisibleByFilter(this.number, this.filter); | |
return this.number; | |
} | |
} | |
// Verify results are the same | |
var primes = new Primes(); | |
var lastPrime = 1; | |
for (let i = 1; i <= 1000; i++) { | |
sievePrive = primes.next() | |
naivePrime = findPrime(lastPrime) | |
lastPrime = naivePrime | |
if (naivePrime != sievePrive || !isPrime(sievePrive)) { | |
throw "Error!" + i | |
} | |
} | |
console.log('OK') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment