使用數字 1-9 各一次,組成三個三位數,使它們的比例為 1:2:3。例如 192:384:576 即為一組解。需編寫 C 程序找出所有滿足條件的組合。
#include
int main() {
int a[9], i, j, k, t, b, c, d, e, p = 1;
for (i = 123; i <= 327; i++) {
b = i; a[0] = b % 10; b /= 10; a[1] = b % 10; b /= 10; a[2] = b;
c = 2 * i; a[3] = c % 10; c /= 10; a[4] = c % 10; c /= 10; a[5] = c;
d = 3 * i; a[6] = d % 10; d /= 10; a[7] = d % 10; d /= 10; a[8] = d;
for (j = 0; j < 9; j++) {
for (k = j + 1; k < 9; k++) {
if (a[j] == a[k]) p = 0;
}
}
if (p) {
for (t = 0; t < 9; t++) {
printf("%d", a[t]);
if (e % 3 == 0) printf("\n");
e++;
}
}
}
return 0;
}
#include
#include
bool check_unique(int x, int y, int z) {
int count[10] = {0};
int nums[3] = {x, y, z};
for (int i = 0; i < 3; i++) {
int n = nums[i];
int d1 = n / 100, d2 = (n / 10) % 10, d3 = n % 10;
if (d1 == 0 || d2 == 0 || d3 == 0) return false; // 不含 0
if (d1 == d2 || d2 == d3 || d1 == d3) return false; // 各數字內部不重複
count[d1]++; count[d2]++; count[d3]++;
}
for (int d = 1; d <= 9; d++) if (count[d] != 1) return false; // 1-9 各恰好一次
return true;
}
int main() {
for (int i = 123; i <= 327; i++) {
int n2 = 2 * i, n3 = 3 * i;
if (check_unique(i, n2, n3)) {
printf("%d %d %d\n", i, n2, n3);
}
}
return 0;
}
程序將輸出四組滿足條件的解:
192 384 576
219 438 657
273 546 819
327 654 981
解決此類數字排列組合問題,關鍵在於:確定正確搜索空間、編寫獨立的校驗函數、注意變量作用域與初始化。將複雜判斷封裝為 `check_unique` 函數,不僅邏輯清晰,也便於調試與複用。