通过置换*3的第一位得到的9个数中,有六个是质数:13,23,43,53,73和83。
通过用同样的数字置换56**3的第三位和第四位,这个五位数是第一个能够得到七个质数的数字,得到的质数是:56003, 56113, 56333, 56443, 56663, 56773, 和 56993。因此其中最小的56003就是具有这个性质的最小的质数。
通过用同样的数字置换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