Skip to content

Instantly share code, notes, and snippets.

@boris-spas
Created October 15, 2021 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boris-spas/bb550d091575c0c682c799961e27fcd6 to your computer and use it in GitHub Desktop.
Save boris-spas/bb550d091575c0c682c799961e27fcd6 to your computer and use it in GitHub Desktop.
// 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