Project Euler NO27

歐拉曾發表過一個著名的二次公式:

n² + n + 41

這個公式對於0到39的連續數字能夠產生40個質數。但是當 n = 40時,402 + 40 + 41 = 40(40 + 1) + 41能夠被41整除。當n = 41時, 41² + 41 + 41顯然也能被41整除。

利用計算機,人們發現了一個驚人的公式:n² − 79n + 1601。這個公式對於n = 0 到 79能夠產生80個質數。這個公式的係數,−79 和1601的乘積是−126479。

考慮如下形式的二次公式:

n² + an + b, 其中|a< 1000, |b< 1000

其中|n| 表示 n 的絕對值。
例如, |11| = 11, |−4| = 4

對於能夠爲從0開始的連續的n產生最多數量的質數的二次公式,找出該公式的係數乘積。


public class Problem27
{
	public static void main(String[] args)
	{
		long start = System.currentTimeMillis();
		System.out.print("answer:  ");
		
		multi();
		
		long end = System.currentTimeMillis();
		System.out.print("time:  ");
		System.out.println(end - start);
	}
	
	static void multi()
	{
		int max = 0;
		int answer = 0;
		for (int i = -999; i < 1000; i++)
		{
			for (int j = 2; j < 1000; j++)
			{
				int had = 0;
				for (int n = 1;; n++)
				{
					int m = n * n + i * n + j;
					if (m < 0)
					{
						break;
					}
					if (check(m))
					{
						had++;
					}
					else 
					{
						break;
					}
				}
				
				if (max < had)
				{
					max = had;
					answer = i * j;
				}
			}
		}
		System.out.println(answer);
	}
	
	static boolean check(int n)
	{
		for (int i = 2; i * i <= n; i++)
		{
			if (n % i == 0)
			{
				return	false;
			}
		}
		
		return true;
	}
	
	
}



answer:  -59231
time:  83

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