Project Euler NO51

通過置換*3的第一位得到的9個數中,有六個是質數:13,23,43,53,73和83。
通過用同樣的數字置換56**3的第三位和第四位,這個五位數是第一個能夠得到七個質數的數字,得到的質數是:56003, 56113, 56333, 56443, 56663, 56773, 和 56993。因此其中最小的56003就是具有這個性質的最小的質數。

找出最小的質數,通過用同樣的數字置換其中的一部分(不一定是相鄰的部分),能夠得到八個質數。




思路:

需要替代的“若干位”的*是相同的,所以一共有10種替代方法,最小的那個質數肯定含有0或1或2,搜索驗證即可


import java.util.ArrayList;
import java.util.List;


public class Problem51
{
	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()
	{
		for (int i = 56003;  ; i++)
		{
			if (iszhishu(i))
			{
				if(zhihuan(i))
				{
					break;
				}
			}
		}
	}
	
	static boolean zhihuan(int n)
	{
		int t = n;
		int len = (n + "").length();
		int arr[] = new int [len];
		int index = len - 1;
		while (n != 0)
		{
			arr[index] = n % 10;
			n /= 10;
			index--;
		}
		List<Integer> zh0 = new ArrayList<>();
		List<Integer> zh1 = new ArrayList<>();
		List<Integer> zh2 = new ArrayList<>();
		for (int i = 0; i < arr.length; i++)
		{
			if (arr[i] == 0)
			{
				zh0.add(i);
			}
			else if (arr[i] == 1)
			{
				zh1.add(i);
			}
			else if (arr[i] == 2)
			{
				zh2.add(i);
			}
			
		}
		
		if (zh0.size() != 0)
		{
			if (isan(arr, zh0, 1))
			{
				System.out.println(0);
				return true;
			}
		}
		else if (zh1.size() != 0)
		{
			if (isan(arr, zh1, 2))
			{
				System.out.println(t);
				return true;
			}
		}
		else if (zh2.size() != 0)
		{
			if (isan(arr, zh2, 3))
			{
				System.out.println(2);
				return true;
			}
		}
		
		return false;
	}
	
	static boolean isan(int arr[], List<Integer> zh, int start)
	{
		int temp[] = arr.clone();
		int nu = 1;
		for (int i = start; i <= 9; i++)
		{
			int s = 0;
			for (int j = 0; j < zh.size(); j++)
			{
				temp[zh.get(j)] = i;
			}
			for (int j = 0; j < temp.length; j++)
			{
				s = s * 10 + temp[j];
			}
			if (iszhishu(s))
			{
				nu++;
			}
		}
		
		if (nu == 8)
		{
			return true;
		}
		
		return false;
	}
	
	static boolean iszhishu(int n)
	{
		for (int i = 2; i <= Math.sqrt(n); i++)
		{
			if (n % i == 0)
			{
				return false;
			}
		}
		
		return true;
	}
}



answer:  121313
time:  150


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