1个四位数乘以1个一位数等于另1个四位数,组成这三个数的9个数字分别是1~9里的任意数,且不重复。请按顺序输出这三个数:
输出结果应该是:
173846952
196347852
共两组。
下面这段是我编的程序,哪里错了?怎么改正?
void pm(int n)
{int i,a[9];
if(n==0) return;
else for(i=1;i<=9;i++)
{a[n-1]=i;pm[n-1];}
if((a[0]*1000+a[1]*100+a[2]*10+a[3])*a[4]==(a[5]*1000+a[6]*100+a[7]*10+a[8]))
{for(i=0;i<9;i++) printf("%d",a[i]);printf("\n");}}
main()
{pm(9);}
void pm(int n)
{int i,a[9];
if(n==0) return;
else for(i=1;i<=9;i++)
{a[n-1]=i;pm[n-1];}//pm()是函数,不是数组,把[]改成(),不过改完后你这循环套递归,递归套循环,
//想不出来最后是什么结果,建议好好研究重新写个清晰的代码
if((a[0]*1000+a[1]*100+a[2]*10+a[3])*a[4]==(a[5]*1000+a[6]*100+a[7]*10+a[8]))
{for(i=0;i<9;i++) printf("%d",a[i]);printf("\n");}}
main()
{pm(9);}
以下代码输出的结果是正确的:
#include <vector>
using namespace std;
#define BITSUM 4
typedef struct Num_struct
{
int val;
bool used;
} Num_t;
Num_t num[9];
int x1[4], x2[4], x3; //x1是第一组的4位数,x3是第二个数,x2是结果的4位数
vector<int> v1, v2;//分别存放X1和X2的排列组合结果
int find_unused()
{
for (int i = 0; i < 9; i++)
{
if (num[i].used)
continue;
return i;
}
return -1;
}
void check()
{
int i = 0, j = 0, k = 0, l = 0;
int a = 0;
//第一组4位数排列
v1.clear();
for (i = 0; i < BITSUM; i++)
{
for (j = 0; j < BITSUM; j++)
{
if (j == i)
continue;
for (k = 0; k < BITSUM; k++)
{
if (k == j || k == i)
continue;
for (l = 0; l < BITSUM; l++)
{
if (l == i || l == j || l == k)
continue;
a = x1[i] * 1000 + x1[j] * 100 + x1[k] * 10 + x1[l];
v1.push_back(a);
}
}
}
}
//结果4位数排列
v2.clear();
for (i = 0; i < BITSUM; i++)
{
for (j = 0; j < BITSUM; j++)
{
if (j == i)
continue;
for (k = 0; k < BITSUM; k++)
{
if (k == j || k == i)
continue;
for (l = 0; l < BITSUM; l++)
{
if (l == i || l == j || l == k)
continue;
a = x2[i] * 1000 + x2[j] * 100 + x2[k] * 10 + x2[l];
v2.push_back(a);
}
}
}
}
int v1_size = v1.size();
int v2_size = v2.size();
for (i = 0; i < v1_size; i++)
{
for (j = 0; j < v1_size; j++)
{
if (v1[i] * x3 == v2[j])//符合条件、输出结果
{
printf("%d * %d = %d\n", v1[i], x3, v2[j]);
}
}
}
}
int pm(int start, int layer)
{
if (layer == BITSUM)
{
int j = 0, k = 0, n;
for ( j = 0; j < 9; j++)
{
if (num[j].used)
continue;
//查找第二个数x3,
x3 = num[j].val;
num[j].used = true;
//查找第三组的4位数x2,
for (k = 0; k < BITSUM; k++)
{
n = find_unused();
x2[k] = num[n].val;
num[n].used = true;
}
check();//检查是否有符合条件的
num[ x3 - 1].used = false;
for (k = 0; k < BITSUM; k++)
{
num[ x2[k] - 1 ].used = false;
}
}
return 0;
}
int i = start - 1;
for (; i >= 0; i--)
{
if (num[i].used)
continue;
//查找第一组的4位数x1,
num[i].used = true;
x1[layer] = num[i].val;
pm(i, layer+1);//递归查找
num[i].used = false;
}
return 0;
}
int main(int argc, char* argv[])
{
for (int i = 0; i < 9; i++)
{
num[i].val = i+1;
num[i].used = false;
}
pm(9, 0);
return 0;
}