Project Euler NO35

我們稱197爲一個循環質數,因爲它的所有輪轉形式: 197, 971和719都是質數。
100以下有13個這樣的質數: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 和97.

100萬以下有多少個循環質數?



public class Problem35
{
	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 sum = 13;
		boolean iszhishu[] = new boolean[1000001];
		for (int i = 100; i <= 1000000; i++)
		{
			if (check(i))
			{
				iszhishu[i] = true;
			}
		}
		
		for (int i = 100; i <= 1000000; i++)
		{
			if (iszhishu[i])
			{
				boolean isanswer = true;
				String str = i + "";
				for (int j = 1; j < str.length(); j++)
				{
					str =str.substring(1) + str.substring(0,1);
					if (!iszhishu[Integer.parseInt(str)])
					{
						isanswer = false;
						break;
					}
				}
				
				if (isanswer)
				{
					sum++;
				}
			}
		}
		System.out.println(sum);
	}
	
	
	static boolean check(int n)
	{
		for (int i = 2; i <= Math.sqrt(n); i++)
		{
			if (n % i == 0)
			{
				return false;
			}
		}
		return true;
	}
}



answer:  55
time:  593

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