Project Euler NO50

41這個質數,可以寫作6個連續質數之和:

41 = 2 + 3 + 5 + 7 + 11 + 13

這是100以下的最長的和爲質數的連續質數序列。

1000以下最長的和爲質數的連續質數序列包含21個項,和爲953.

找出100萬以下的最長的何爲質數的連續質數序列之和。

100萬以下的哪個質數能夠寫成最長的連續質數序列?


public class Problem50
{
	public static void main(String[] args)
	{
		long start = System.currentTimeMillis();
		System.out.print("answer:  ");
		
		howmany();
		
		long end = System.currentTimeMillis();
		System.out.print("time:  ");
		System.out.println(end - start);
	}
	
	static void howmany()
	{
		boolean array[] = new boolean[1000000];
		
		for (int i = 2; i < 1000000; i++)
		{
			array[i] = iszhishu(i);
		}
		
		int answer = 0;
		int maxlen = 0;
		for (int i = 2; i < 1000000; i++)
		{
			int len = 0;
			int t = 0;
			if (array[i])
			{
				for (int j = i; j < 1000000; j++)
				{
					if (array[j])
					{
						len++;
						t += j;
						if (t >= 1000000)
						{
							break;
						}
						
						if (array[t] && len > maxlen)
						{
							maxlen = len;
							answer = t;
						}
					}
				}
			}
			
		}
		System.out.println(answer);
	}
	
	static boolean iszhishu(int n)
	{
		for (int i = 2; i <= Math.sqrt(n); i++)
		{
			if (n % i == 0)
			{
				return false;
			}
		}
		
		return true;
	}
}




answer:  997651
time:  502



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章