《入门经典》第2章习题2-6

题目:用1~9组成3个三位数 abc, def 和 ghi,每个数字恰好使用一次,要求 abc:def:ghi=1:2:3。按照“abc def ghi”的格式输出所有解,每行一个解。

虽说题目上给的提示是不必太动脑筋,但说实话刚刚看到这题我一点思路都没有。最后想的办法是,先将所有符合1:2:3的三位数组合找出来,再分别拆分他们的各个数字。最后卡住的点是如何判断数字没有重复,之前的经验告诉我,像下面的代码段是绝对行不通的(原因我没搞懂但是确实行不通):

a1!=a2!=a3!=b1!=b2!=b3!=c1!=c2!=c3

之后搜了相关题目才了解到,1~9九个数字的和为45,积为362880可以用来判断,至此本题得解。

代码如下:

#include <iostream>
using namespace std;
int main() {
	int arr[1000], brr[1000], crr[1000], n = 0;
	for (int i = 100; i < 1000; i++) {
		if (i * 3 < 1000) {
			arr[n] = i;
			brr[n] = i * 2;
			crr[n] = i * 3;
			n++;
		}
	}
	for (int j = 0; j < n - 1; j++) {
		int a1 = arr[j] % 10;
		int a2 = arr[j] / 10 % 10;
		int a3 = arr[j] / 100;
		int b1 = brr[j] % 10;
		int b2 = brr[j] / 10 % 10;
		int b3 = brr[j] / 100;
		int c1 = crr[j] % 10;
		int c2 = crr[j] / 10 % 10;
		int c3 = crr[j] / 100;
		if (a1 + a2 + a3 + b1 + b2 + b3 + c1 + c2 + c3 == 45 && a1*a2*a3*b1*b2*b3*c1*c2*c3 == 362880)
			cout << arr[j] << " " << brr[j] << " " << crr[j] << endl;
	}
}
发布了7 篇原创文章 · 获赞 0 · 访问量 54

猜你喜欢

转载自blog.csdn.net/qq_21606413/article/details/104755463
2-6
今日推荐