本文主要是介绍火柴棍等式--枚举,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
火柴棍等式
要求
用m(m <= 24)根火柴棍拼出A+B=C的等式,数字非零,则最高位不能是0,加号和等号各用了两根火柴棍,问可以拼出多少个不同等式?
思路
枚举法
代码
#include <stdio.h>#define M 18int fun(int x) {int a[10] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};int sum = 0;while(x / 10 != 0) {sum += a[x%10];x = x/10;}sum += a[x];return sum;
}int main()
{int a, b, c; for (int a = 0; a <= 11111; ++a) { //M最大24,20根火柴最多组成10个1for (int b = 0; b <= 11111; ++b) {c = a + b;if (fun(a) + fun(b) + fun(c) == M - 4){printf("%d + %d = %d\n", a, b, c);}}}return 0;
}
结果
0 + 4 = 4
0 + 11 = 11
1 + 10 = 11
2 + 2 = 4
2 + 7 = 9
4 + 0 = 4
7 + 2 = 9
10 + 1 = 11
11 + 0 = 11
python 代码
M = 18def fun(x):a = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]sm = 0while int(x/10) != 0:sm = sm + a[x%10]x = int(x / 10)sm = sm + a[x]return smfor a in range(11112):for b in range(11112):c = a + bif fun(a) + fun(b) + fun(c) == M - 4:print("%d + %d = %d" % (a, b, c))
这篇关于火柴棍等式--枚举的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!