1.package com.shui.mu.yao.io.algorithm;
2.
3.import java.util.ArrayList;
4.import java.util.Arrays;
5.import java.util.List;
6.
7./**
8. *
9. * @author shuimuqinghua77 @date 2011-11-3下午07:44:42
10. */
11./**
12. * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the
13. * primes below two million.
14. */
15.public class Problem10 {
16. private static List<Long> seed = new ArrayList<Long>();
17.
18. private static void initSeed(long[] seeds) {
19. for (long i : seeds)
20. seed.add(i);
21. }
22.
23. public static long sumBelowTop(long top) {
24. initSeed(new long[] { 2 });
25. long middle = (long) Math.sqrt(top);
26. for (long k = 2, factor = 2, i = factor * k - 1; i < top; factor++, i = factor
27. * k - 1) {
28. boolean isPrime = true;
29. for (long s : seed) {
30. if (s > middle)
31. break;
32. if (i % s == 0) {
33. isPrime = false;
34. break;
35. }
36.
37. }
38. if (isPrime)
39. seed.add(i);
40. }
41. long sum = 0;
42. for (long s : seed) {
43. sum += s;
44. }
45. return sum;
46.
47. }
48.
49. public static void main(String[] args) {
50. long sum = sumBelowTop(2000000l);
51. // System.out.println(Arrays.toString(seed.toArray()));
52. System.out.println(sum);
53. }
54.}