Find prime numbers using Scala. Help me to improve

Here’s a functional implementation of the Sieve of Eratosthenes, as presented in Odersky’s “Functional Programming Principles in Scala” Coursera course : // Sieving integral numbers def sieve(s: Stream[Int]): Stream[Int] = { s.head #:: sieve(s.tail.filter(_ % s.head != 0)) } // All primes as a lazy sequence val primes = sieve(Stream.from(2)) // Dumping the first five … Read more

Parallel Algorithms for Generating Prime Numbers (possibly using Hadoop’s map reduce)

Here’s an algorithm that is built on mapping and reducing (folding). It expresses the sieve of Eratosthenes      P = {3,5,7, …} \ U {{p2, p2+2p, p2+4p, …} | p in P} for the odd primes (i.e without the 2). The folding tree is indefinitely deepening to the right, like this: where each prime number … Read more

Speed up bitstring/bit operations in Python?

There are a couple of small optimizations for your version. By reversing the roles of True and False, you can change “if flags[i] is False:” to “if flags[i]:“. And the starting value for the second range statement can be i*i instead of i*3. Your original version takes 0.166 seconds on my system. With those changes, … Read more

Generating integers in ascending order using a set of prime numbers

Removing a number and reinserting all its multiples (by the primes in the set) into a priority queue is wrong (in the sense of the question) – i.e. it produces correct sequence but inefficiently so. It is inefficient in two ways – first, it overproduces the sequence; second, each PriorityQueue operation incurs extra cost (the … Read more

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