-1

I have written the following block of code to calculate the sum of all the primes below a certain number-2 000 000 in this case to be precise, however it takes quite some time to execute; 20 second:

def summation_of_primes_below_n(n):
list = []
sum = 0
for i in range(2, n):
    if checks_if_prime(i) == True:
        list.append(i)
return list
for j in list:
    sum = sum + j
return sum

def checks_if_prime(n):
    if n == 2:
        return True
    import math
    for i in range(2, math.ceil(math.sqrt(n))+1):
        if n%i == 0:
            return False
        elif i == math.ceil(math.sqrt(n)):
            return True

print(summation_of_primes_below_n(2000000))

So I was wondering if there was a way to make my code more efficient. I would greatly appreciate suitable advice on the same. Also, I would prefer that you give more basic solutions since I am a beginner and provide the logic for the same. Thanks a lot!

Aradhye Agarwal
  • 319
  • 1
  • 2
  • 8

1 Answers1

2

You can start off by implementing some better algorithm. For eg: Sieve of Eratosthenes

Or if you are happy with your current logic, then few optimizations that can help:

  • Check only for odd numbers:

    for i in range(3, n, 2):

  • Check only for numbers of form 6n+1, 6n+5

  • You don't need to do this check : elif i == math.ceil(math.sqrt(n)): for each iteration. If the control reached beyond the loop then the number is prime

  • You can convert your check_prime to generator pattern. Could save some redundancy and possibly improve locality of reference.

Community
  • 1
  • 1
bashrc
  • 4,426
  • 1
  • 18
  • 45