标题: 组素数
素数就是不能再进行等分的数。比如:2 3 5 7 11 等。9 = 3 * 3 说明它可以3等分,因而不是素数。
我们国家在1949年建国。如果只给你 1 9 4 9 这4个数字卡片,可以随意摆放它们的先后顺序(但卡片不能倒着摆
放啊,我们不是在脑筋急转弯!),那么,你能组成多少个4位的素数呢?
比如:1949,4919 都符合要求。
请你提交:能组成的4位素数的个数,不要罗列这些素数!!
注意:不要提交解答过程,或其它的辅助说明文字。
解析:
方案一:使用四组循环进行嵌套所有情况
import java.util.HashSet;
import java.util.Set;
public class Test {
static Set<Integer> set = new HashSet<Integer>();
public static void main(String[] args)
{
int[] arr = new int[]{1,9,4,9};
for (int a = 0; a < arr.length; a++)
{
for (int b = 0; b < arr.length; b++)
{ if(b==a) continue;
for (int c = 0; c < arr.length; c++)
{ if(c==a || c == b) continue;
for (int d = 0; d < arr.length; d++)
{ if(d==a || d==b || d==c) continue;
int num = arr[a]*1000+arr[b]*100+ arr[c]*10+arr[d];
boolean isSushu = true; //假设是素数
for (int i = 2; i <= Math.sqrt(num); i++)
{
if(num%i==0)
{
isSushu = false;
break;
}
}
if(isSushu == true)
{
//System.out.println(num);
set.add(num);
}
}
}
}
}
System.out.println(set.size());
}
}
执行结果:
6
方案二:借助全排列的固定算法,如下:
下面的代码可以将1,2,3,三个数字的所有排列组合进行打印。
public static void main(String[] args)
{
int[] arr = new int[]{1,2,3};
fullSort(arr,0,arr.length-1);
}
public static void fullSort(int[] arr,int start,int end)
{
if(start == end)
{
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
}
System.out.println();
}
for (int i = start; i <=end; i++) {
swap(arr,start,i);
fullSort(arr,start+1,end);
swap(arr,start,i);
}
}
public static void swap(int[] arr,int i,int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
本题代码:
import java.util.HashSet;
import java.util.Set;
public class Demo02 {
static Set<Integer> set = new HashSet<Integer>();
public static void main(String[] args)
{
int[] arr = new int[]{1,9,4,9};
fullSort(arr,0,arr.length-1);
System.out.println(set.size());
}
public static void fullSort(int[] arr,int start,int end)
{
if(start == end)
{
int x = arr[0]*1000+arr[1]*100+arr[2]*10+arr[3];
boolean isSushu = true; //假设是素数
for (int i = 2; i <= Math.sqrt(x); i++)
{
if(x%i==0)
{
isSushu = false;
break;
}
}
if(isSushu == true)
{
//System.out.println(x);
set.add(x);
}
}
for (int i = start; i <=end; i++) {
swap(arr,start,i);
fullSort(arr,start+1,end);
swap(arr,start,i);
}
}
public static void swap(int[] arr,int i,int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
执行结果:
6