Created
September 19, 2018 02:58
-
-
Save adithyaxx/8dcf98888eae90201e8b11a85f125951 to your computer and use it in GitHub Desktop.
A python script to calculate the sum of all prime numbers less than n
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sum_primes(limit): | |
primes = [] | |
for n in range(2, limit+1): | |
# try dividing n with all primes less than sqrt(n): | |
for p in primes: | |
if n % p == 0: break # if p divides n, stop the search | |
if n < p*p: | |
primes.append(n) # if p > sqrt(n), mark n as prime and stop search | |
break | |
else: primes.append(n) # fallback: we actually only get here for n == 2 | |
return sum(primes) | |
print(sum_primes(5000000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment