问题描述
农民约翰母牛总是产生最好的肋骨。你能通过农民约翰和美国农业部标记在每根肋骨上的数字认出它们。农民约翰确定他卖给买方的是真正的质数肋骨,是因为从右边开始切下肋骨,每次还剩下的肋骨上的数字都组成一个质数。例如有四根肋骨的数字分别是:7 3 3 1,那么全部肋骨上的数字 7331是质数;三根肋骨 733是质数;二根肋骨 73
是质数;当然,最后一根肋骨 7 也是质数。7331 被叫做长度 4 的特殊质数。写一个程序对给定的肋骨的数目 N (1<=N<=8),求出所有的特殊质数。数字1不被看作一个质数。 输入格式 单独的一行包含N。
输出格式 按顺序输出长度为 N 的特殊质数,每行一个。
样例输入 4
样例输出 2333 2339 2393 2399 2939 3119 3137 3733 3739 3793 3797 5939 7193 7331 7333 7393
import java.util.Scanner;
class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N=sc.nextInt();
int[] nums=new int[N];
helper(nums,N,0);
}
//全排列DFS
public static void helper(int[] nums,int N,int curr){
if(N==curr){
if(check(nums,N)){
for (int i :nums) {
System.out.print(i);
}
System.out.println();
}
}else{
for (int i=1;i<=9;i++){//直接从1开始,因为如果数中有0,那么必不可能全是质数
nums[curr]=i;
helper(nums,N,curr+1);
}
}
}
//判断前初始化
private static boolean check(int[] nums,int N) {
int x=0;
for (int i=0;i<N;i++){
x= (int) (x*10+nums[i]);//注意取数方法
if(!is_zhishu(x)) return false;
}
return true;
}
//判断质数
private static boolean is_zhishu(int x){
if(x==1)return false;
if(x==2||x==3) return true;
else {
for (int i = 2; i <Math.sqrt(x)+1 ; i++) {
if(x%i==0) return false;
}
}return true;
}
}