Problem10_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Problem10

Problem10

 2011/11/4 8:11:19  水木清华77  http://1031709750-qq-com.iteye.com  我要评论(0)
  • 摘要:packagecom.shui.mu.yao.io.algorithm;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;/****@authorshuimuqinghua77@date2011-11-3下午07:44:42*//***Thesumoftheprimesbelow10is2+3+5+7=17.Findthesumofallthe*primesbelowtwomillion
  • 标签:
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);
	}
}
  • 相关文章
发表评论
用户名: 匿名