Skip to content

Instantly share code, notes, and snippets.

@adithyaxx
Created September 19, 2018 02:58
Show Gist options
  • Save adithyaxx/8dcf98888eae90201e8b11a85f125951 to your computer and use it in GitHub Desktop.
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
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