Created
September 25, 2017 11:44
-
-
Save javamultiplex/f7eba6abe232fb16f42bac4916315fbb to your computer and use it in GitHub Desktop.
Project Euler Problem 10 : Sum of all primes below 2 million
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment