Sieve of Eratosthenes – Finding Primes Python

You’re not quite implementing the correct algorithm: In your first example, primes_sieve doesn’t maintain a list of primality flags to strike/unset (as in the algorithm), but instead resizes a list of integers continuously, which is very expensive: removing an item from a list requires shifting all subsequent items down by one. In the second example, … Read more

Python Finding Prime Factors

This question was the first link that popped up when I googled “python prime factorization”. As pointed out by @quangpn88, this algorithm is wrong (!) for perfect squares such as n = 4, 9, 16, … However, @quangpn88’s fix does not work either, since it will yield incorrect results if the largest prime factor occurs … Read more

How to create the most compact mapping n → isprime(n) up to a limit N?

The fastest algorithm for general prime testing is AKS. The Wikipedia article describes it at lengths and links to the original paper. If you want to find big numbers, look into primes that have special forms like Mersenne primes. The algorithm I usually implement (easy to understand and code) is as follows (in Python): def … Read more

Why use a prime number in hashCode?

Prime numbers are chosen to best distribute data among hash buckets. If the distribution of inputs is random and evenly spread, then the choice of the hash code/modulus does not matter. It only has an impact when there is a certain pattern to the inputs. This is often the case when dealing with memory locations. … Read more

Fastest way to list all primes below N

Warning: timeit results may vary due to differences in hardware or version of Python. Below is a script which compares a number of implementations: ambi_sieve_plain, rwh_primes, rwh_primes1, rwh_primes2, sieveOfAtkin, sieveOfEratosthenes, sundaram3, sieve_wheel_30, ambi_sieve (requires numpy) primesfrom3to (requires numpy) primesfrom2to (requires numpy) Many thanks to stephan for bringing sieve_wheel_30 to my attention. Credit goes to Robert … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)