Project Euler 10: Summation of primes

Summation of primes

Summation of primes

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Official Problem

Solution Approach

In this problem of Summation of primes till 1 million, we are supposed to find the sum of all the prime numbers in the range of 1 to 1 million.

We are given a range of numbers to which we have to find the prime numbers. This makes it the best scenario to use the Sieve of Eratosthenes method of finding prime numbers. We will essentially take numbers from 1 to 1 million and eliminate the numbers if they are divisible by 2, 3, 5, and so on. This process is repeated till 1000 as 1000 is the root of 1 million. After we identified the prime numbers by eliminating all the non-prime ones we just have to add them. The sum (upper bound will be 20000002) will be lesser than the integer’s capacity hence we can use an integer to store the value.

The time complexity of this approach is O(N log N) as we iterate through the numbers once and with each iteration we have fewer numbers to iterate through. The space complexity is 1 million to store all the data but it is constant i.e we know beforehand how much space is required, hence O(1).

Coming to the code of this approach we will have to initialize an array having 1 million space with the initial value is true. We also have to have a variable to store the sum. Secondly, we use the Sieve of Eratosthenes method to eliminate all the non-prime numbers by marking their position as false. This process is repeated till the square root of 1 million. After that, the array positions which are prime numbers will have true as their value. In the end, we will add those positions to get the final result.

Solution Code

Java Solution

Python Solution

For more Project Euler explained solutions visit Project Euler Detailed Solutions.

For Leetcode detailed solutions go to Leetcode Detailed Solutions.

If you like capture the flag challenges visit here.

Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via the Contact page I will surely respond. Happy Coding.

Leave a Comment

Your email address will not be published. Required fields are marked *