Project Euler NO58

從1開始逆時針旋轉,可以得到一個邊長爲7的螺旋正方形。

37 36 3534 33 32 31
38 17 16 15 14 13 30
39 18  5  4  3 12 29
40 19  6 1  2 11 28
41 20  7  8  9 10 27
42 21 2223 24 25 26
43 44 45 46 47 48 49

有趣的是奇數的平方數都處於右下對角線上。更有趣的是,對角線上的13個數字中有8個質數,其百分比是8/13 ≈ 62%。

如果在上面的螺旋正方形上再加一層,可以得到一個邊長爲9的螺旋正方形。如果這個過程繼續,到螺旋正方形的邊長爲多少時,對角線上的質數百分比第一次降到10%以下?

public class Problem58
{
	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()
	{
		int t = 1;
		double up = 0;
		int down = 0;
		for (int i = 1; ; i++)
		{
			down ++;
			t += (i + 1) / 2;
			if ((i+3) % 4 != 0)
			{
				if (iszhishu(t))
				{
					up++;
				}
			}
			else 
			{
				if (up / down < 0.1 && t != 2)
				{
					System.out.println((int)Math.sqrt(t - 1));
					break;
				}
			}
		}
	}
	
	static boolean iszhishu(int n)
	{
		for (int i = 2; i <= Math.sqrt(n); i++)
		{
			if ( n % i == 0)
			{
				return false;
			}
		}
		
		return true;
	}
}



answer:  26241
time:  577



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