Name: Anonymous 2006-08-17 19:07
I'm testing something to kill time. Can I ask for an efficient Perl, Java, C and C++ implementations of the following Python? (Also, if you have any ideas on how to make this more efficient in Python, you're welcome to own me.)
The first function calculates primes up to max using a classic algorithm. Do not change the algorithm, just try to make the code as fast as possible; tricks allowed as long as you stick to this algorithm.
The second function implements a Sieve of Eratosthenes using dictionaries (hashes), which takes an assload of memory but is much faster. Again, don't change the algorithm, but you can use any data structure you see fit.
tl;dr version: Could you port the following into efficient Perl, Java, C and C++? No need to understand what they do.
The first function calculates primes up to max using a classic algorithm. Do not change the algorithm, just try to make the code as fast as possible; tricks allowed as long as you stick to this algorithm.
The second function implements a Sieve of Eratosthenes using dictionaries (hashes), which takes an assload of memory but is much faster. Again, don't change the algorithm, but you can use any data structure you see fit.
tl;dr version: Could you port the following into efficient Perl, Java, C and C++? No need to understand what they do.
def Primes(max):
a = []
for i in xrange(1, max + 1):
prime = True
for j in xrange(2, int(sqrt(i)) + 1):
if not i % j:
prime = False
break
if prime:
a += [i]
return a
def Erat(size):
size1 = size + 1
s = dict.fromkeys(xrange(2, size1), None)
for n in xrange(2, int(sqrt(size)) + 1):
if n in s:
for i in xrange(n << 1, size1, n):
if i in s:
del s[i]
return [1] + list(s)