JavaAlgorithms/ProjectEuler/Problem10.java

56 lines
1.1 KiB
Java
Raw Normal View History

package ProjectEuler;
/**
* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
2020-10-24 18:23:28 +08:00
*
* <p>Find the sum of all the primes below two million.
*
* <p>link: https://projecteuler.net/problem=10
*/
public class Problem10 {
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
long[][] testNumbers = {
{2000000, 142913828922L},
{10000, 5736396},
{5000, 1548136},
{1000, 76127},
{10, 17},
{7, 10}
};
2020-10-24 18:23:28 +08:00
for (long[] testNumber : testNumbers) {
assert solution1(testNumber[0]) == testNumber[1];
}
2020-10-24 18:23:28 +08:00
}
2020-10-24 18:23:28 +08:00
/***
* Checks if a number is prime or not
* @param n the number
* @return {@code true} if {@code n} is prime
*/
private static boolean isPrime(int n) {
if (n == 2) {
return true;
}
2020-10-24 18:23:28 +08:00
if (n < 2 || n % 2 == 0) {
return false;
}
for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
2020-10-24 18:23:28 +08:00
private static long solution1(long n) {
long sum = 0;
for (int i = 2; i < n; ++i) {
if (isPrime(i)) {
sum += i;
}
}
2020-10-24 18:23:28 +08:00
return sum;
}
}