Created
July 24, 2013 23:48
-
-
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.
This file contains hidden or 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
| 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; | |
| } | |
| } |
This file contains hidden or 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
| 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