用 0,1,2,3 \cdots 70,1,2,3⋯7 这 88 个数组成的所有整数中,质数有多少个(每个数字必须用到且只能用一次)。
提示:以 00 开始的数字是非法数字。
暴力解决:
import java.util.Scanner;
import java.util.Arrays;
public class M {
static int s;
static int sum;
//素数判断函数
public static boolean su(double n){
double s=Math.sqrt(n);
for(int i=2;i<=s;i++)
if(n%i==0)return false;
return true;
}
public static void main(String[] args) {
//暴力排列组合
for (int a = 1; a < 8; a++) {
for (int b = 0; b < 8; b++) {
for (int c = 0; c <8; c++) {
for (int d = 0; d <8; d++) {
for (int e = 0; e < 8; e++) {
for (int f = 0; f < 8; f++) {
for (int g = 0; g < 8; g++) {
for (int h = 0; h < 8; h++) {
s=a*10000000+b*1000000+c*100000+d*10000+e*1000+f*100+g*10+h;
if ( (a != b) && (a != c) && (a != d) & (a != e) && (a != f) && (a != g)&& (a != h)
&& (b != c) && (b != d) & (b != e)&& (b != f) && (b != g) && (b != h)
&& (c != d) & (c != e) && (c != f) && (c != g) && (c != h)
&& (d != e) && (d != f) && (d != g) && (d != h)
&& (e != f) && (e != g) && (e != h)
&& (f != g) && (f != h) && (g != h)&&su(s)){
//System.out.println(s);
sum++;
}
}
}
}
}
}
}
}
}
System.out.println(sum);
}
}
下面是参考别人的1-9排列组合
import java.util.Scanner;
import java.lang.Math;
public class Main {
public static void main(String[] args) {
String str[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
permutation(str, 0, str.length);
}
static void swap(String[] str, int start, int end) {
String tmep = str[start];
str[start] = str[end];
str[end] = tmep;
}
static void permutation(String[] str, int start, int end) {
if (start == end - 1) {
for (int i = 0; i < end; i++) {
System.out.print(str[i]);
}
System.out.println();
} else {
for (int i = start; i < end; i++) {
if (i == 0 && str[0].equals("0"))
continue;
swap(str, start, i);
permutation(str, start + 1, end);
swap(str, start, i);
}
}
}
}