In this post I have written a program in Python which tries to find out the sum of all prime numbers below a number. I have implemented the solution in Python. This problem was originally posted on Project Euler and it asked to find the sum of all prime numbers below two Million. Seems exciting, right?

Recently I have been experimenting with various problems related to prime numbers and trying to implement in Python. I also came across Trinket.Io. This is a fabulous way to embed python interpreter in a browser for academic and learning purposes and it helps two causes:

- An algorithms enthusiast like me who just wants to see how the algorithm works and how can we make it faster and better. Most likely I am interested to see the code but before that I am more likely to learn more about the efficiency of algorithm. So I can directly tweak the algorithm in Trinket in browser and see what I see in output.
- A novice who is not aware of installing Python and just wants to see first how the specific programming problem can be solved using Python.

### Python (programming language)

If you have Python terminal installed on your Unix or Python IDLE editor on Windows Machine, then make a new .py file and run in the terminal following command:

execfile("SumOfPrimeNumbers.py")

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | """ In order to use this python code, just change the value of i. """ def main(): summation= x=[] i=2000000 x=primes_upto(i) summation=sum(x) print summation def primes_upto(limit): is_prime = [False] * 2 + [True] * (limit - 1) for n in range(int(limit**0.5 + 1.5)): # stop at ``sqrt(limit)`` if is_prime[n]: for i in range(n*n, limit+1, n): is_prime[i] = False return [i for i, prime in enumerate(is_prime) if prime] if __name__ == '__main__': main() |

### What if Python is Not Installed

Go to Repl.it and write the below code which I have customized so that you directly run the code and see the output.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | """ In order to use this python code, just change the value of i. """ def primes_upto(limit): is_prime = [False] * 2 + [True] * (limit - 1) for n in range(int(limit**0.5 + 1.5)): # stop at ``sqrt(limit)`` if is_prime[n]: for i in range(n*n, limit+1, n): is_prime[i] = False return [i for i, prime in enumerate(is_prime) if prime] summation= x=[] i=7 x=primes_upto(i) summation=sum(x) print summation |

Please let me know if the code works for you and it would be great if you could write your feedback in comments.