题目
由 4 个不同的数字,组成的一个乘法算式,它们的乘积仍然由这 4 个数字组成。
比如:
- 210 x 6 = 1260
- 8 x 473 = 3784
- 27 x 81 = 2187
如果满足乘法交换律的算式算作同一种情况,那么,包含上边已列出的 3 种情况,一共有多少种满足要求的算式。
代码
#include <cstdio>
#include <algorithm>
using namespace std;
int main()
{
for (int i = 1023; i < 9876; i++)
{
int a = i / 1000;
int b = i / 100 % 10;
int c = i / 10 % 10;
int d = i % 10;
//判断是否相等
if (a == b || a == c || a == d || b == c || b == d || c == d) continue;
int s[4] = { a, b, c, d };
/*
乘积为四位数的结果只有两种情况:
(1)两位数*两位数;
(2)一位数*三位数。
*/
//next_permutation排列组合
while (next_permutation(s, s + 4))
{
if (s[0] * (s[1] * 100 + s[2] * 10 + s[3]) == i)
printf("%d * %d%d%d\n", s[0], s[1], s[2], s[3]);
if ((s[0] * 10 + s[1]) * (s[2] * 10 + s[3]) == i)
printf("%d%d * %d%d\n", s[0], s[1], s[2], s[3]);
}
}
return 0;
}
其中,next_permutation参考。
输出结果
6 * 201
21 * 60
60 * 21
6 * 210
15 * 93
93 * 15
35 * 41
41 * 35
3 * 501
30 * 51
3 * 510
51 * 30
21 * 87
87 * 21
27 * 81
81 * 27
9 * 351
8 * 473