Sieve of Eratosthenes algorithm in JavaScript running endless for large number

You are making the Sieve of Eratosthenes much slower by making use of array manipulation functions such as Array#indexOf and Array#splice which runs in linear time. When you can have O(1) for both operations involved. Below is the Sieve of Eratosthenes following conventional programming practices: var eratosthenes = function(n) { // Eratosthenes algorithm to find … Read more

double stream feed to prevent unneeded memoization?

Normally, definition of primes stream in Richard Bird’s formulation of the sieve of Eratosthenes is self-referential: import Data.List.Ordered (minus, union, unionAll) ps = 2 : minus [3..] — `:` is “cons” (foldr (\p r -> p*p : union [p*p+p, p*p+2*p..] r) [] ps) The primes ps produced by this definition are used as the input … Read more

Program to find prime numbers

You can do this faster using a nearly optimal trial division sieve in one (long) line like this: Enumerable.Range(0, Math.Floor(2.52*Math.Sqrt(num)/Math.Log(num))).Aggregate( Enumerable.Range(2, num-1).ToList(), (result, index) => { var bp = result[index]; var sqr = bp * bp; result.RemoveAll(i => i >= sqr && i % bp == 0); return result; } ); The approximation formula for … Read more