题目要求:将1~9这9个数字分成三组,每组中的三个数排成一个三位的完全平方数,要求每个数字必须且只能用一次 。
思路如下:
1、先造一个数组num[]用来标记1到9这几个数字是否已经被使用过。比如:num[1] = 0,表示"1" 还没被使用过,而 num[1] = 1,则表示"1"前面已经用过了,要重新取数。 每次取数之前都判断一下要取的数对应的num[]标志,这样就解决了 “每个数字必须且只能用一次” 。
2、然后是要造一个三位的数,用三层嵌套循环,比如第一层是遍历百位的数 ,从“1”到“9”一直遍历取数字,后面两层同理,最后造的三位数等于:100x百位的数字+10x十位的数字 +个位的数字;
3、得到一个没有重复数字的三位数后就要判断此数是否为完全平方数。判断的方法很简单,就是判断此数的开方是不是整数,是的话就说明这个数是完全平方数,然后把它打印出来。
重复2、3步的操作,执行程序完后输出的三个数是: 169 256 324
#include <stdio.h>
#include <math.h>
int judge_perfect_square(int x){
if (sqrt(x) == (int)sqrt(x))
return 1;
else
return 0;
}
main(){
int i, x, y, z, ps, num[10];
for(i = 1; i < 10; i++) //Initialize num[]
num[i] = 0;
for(x = 1; x < 10; x++){ //hundreds
if(num[x] == 1) //judge whether the number has already been taken
continue;
num[x] = 1; //Make a mark
for(y = 1; y < 10; y++){ //tens
if(num[y] == 1) //Judge whether the number has already been taken
continue;
num[y] = 1; //Make a mark
for(z = 1; z < 10; z++){ //units
if(num[z] == 1) //Judge whether the number has already been taken
continue;
num[z] = 1; //Make a mark
ps = 100*x + 10*y + z; //the three-digit number
if(judge_perfect_square(ps)) //Judge whether the number is perfect square
printf("%d ", ps);
else
num[z] = 0; //clear the mark if the number is not a perfect square
}
num[y] = 0;
}
num[x] = 0;
}
}