Skip to content

Instantly share code, notes, and snippets.

@rfaisal
Created July 24, 2013 23:48
Show Gist options
  • Select an option

  • Save rfaisal/6075670 to your computer and use it in GitHub Desktop.

Select an option

Save rfaisal/6075670 to your computer and use it in GitHub Desktop.
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.
public class SumOfPrimes {
public static long calculate(int n){
long sum=2;
for(int i=3;i<n;i++)
if(isPrime(i))
sum+=i;
return sum;
}
private static boolean isPrime(int p){
for(int i=2;i<=Math.sqrt(p);i++)
if(p%i==0) return false;
return true;
}
}
public class SumOfPrimesTest {
@Test
public void testCalculate() {
assertEquals(17, SumOfPrimes.calculate(10));
assertEquals(142913828922L, SumOfPrimes.calculate(2000000));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment