package com.shui.mu.yao.io.algorithm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author shuimuqinghua77 @date 2011-11-3下午07:44:42
*/
/**
* 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 Problem10 {
private static List<Long> seed = new ArrayList<Long>();
private static void initSeed(long[] seeds) {
for (long i : seeds)
seed.add(i);
}
public static long sumBelowTop(long top) {
initSeed(new long[] { 2 });
long middle = (long) Math.sqrt(top);
for (long k = 2, factor = 2, i = factor * k - 1; i < top; factor++, i = factor
* k - 1) {
boolean isPrime = true;
for (long s : seed) {
if (s > middle)
break;
if (i % s == 0) {
isPrime = false;
break;
}
}
if (isPrime)
seed.add(i);
}
long sum = 0;
for (long s : seed) {
sum += s;
}
return sum;
}
public static void main(String[] args) {
long sum = sumBelowTop(2000000l);
// System.out.println(Arrays.toString(seed.toArray()));
System.out.println(sum);
}
}
Problem10
最新推荐文章于 2024-10-08 21:30:52 发布