Problem10

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);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值