Home > Programming > What is the sum of all primes below two millions?

What is the sum of all primes below two millions?


The idea to minimize the amount of time is that, if a number has factors other than 1 and itself must exist between 2 and square root of that number.

The above constraint reduces innumerable number of comparisons and saves a lot of space too.

Here is the code to find the sum of all primes below two millions.

<blockquote>package projecteuler;

/**
*
* @author Vasanth Raja Chittampally
*/
public class ProjectEuler {

public static void main(String[] args) {
long sum=2;
out: for (long i = 3; i &lt; 2000000; i++) {
if(i%2==0)
continue out;
for (int j = 3; j &lt;=Math.sqrt(i); j+=2) {
if(i%j==0) continue out;
}
sum+=i;

}
System.out.println(""+sum);
}</blockquote>

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: