# Project Euler | Problem 10 | Summation of primes

##
__Problem Description__ :

The sum of the primes below

**10**is

**2 + 3 + 5 + 7 = 17**. Find the sum of all the primes below two million.

##
__Concept__ :

For generating prime numbers we are using Sieve of Eratosthenes algorithm. This is very simple and efficient algorithm for generating primes.

##
__Algorithm__ :

If you want to generate all prime number below N. Please follow below steps.

- Create boolean array of length N and assign 'TRUE' to all elements of an array.
- Find the sqrt of N because loop will run from 2 to sqrt(N).
- In loop, check whether element present at current index is 'TRUE'. If yes, then assign 'FALSE' to all elements whose index is multiple of current index.

Sieve of Eratosthenes algorithm |

Once prime numbers generated, run the loop from 2 to limit(2 million) and check whether element present at current index is prime or not. If element is prime then add that index.

##
__Java Program__ :

package com.javamultiplex.projecteuler; import java.util.Arrays; /** * * @author Rohit Agarwal * @category Project Euler Problems * @problem Sum of all primes below 2 million * */ public class Problem10 { public static void main(String[] args) { int limit = 2000000; // 2 Million long sum = 0; boolean primes[] = new boolean[limit]; // Assign true to all array elements Arrays.fill(primes, true); generatePrimes(primes); for (int i = 2; i < limit; i++) { if (primes[i]) { sum = sum + i; } } System.out.println("The sum of all the primes below two million is : " + sum); } //Sieve of Eratosthenes - Algorithm for generating prime numbers. private static void generatePrimes(boolean[] primes) { int length = primes.length; int sqrt = (int) Math.sqrt(length); for (int i = 2; i <= sqrt; i++) { for (int j = i * i; j < length; j = j + i) { primes[j] = false; } } } }

##
__Output__ :

Output - Project Euler Problem 10 solution in Java |

##
__References__ :

https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html

Thank you friends, I hope you have clearly understood the solution of this problem. If you have any doubt, suggestion or query please feel free to comment below. You can also discuss this solution in our forum.

**Tags : Project Euler Problem 10 solution in Java, Prime numbers, Summation of primes, Mathematics problems, if else statement, for loop, Eratosthenes Algorithm, Arrays.**

Project Euler | Problem 10 | Summation of primes
Reviewed by Rohit Agarwal
on
3/31/2017
Rating:

## No comments:

Please provide your valuable comments. If you have any suggestion please share with me I will work on it and if you have any question or doubt please ask, don't hesitate. I am your friend, i will clarify all your doubts.