仅打印那些总和为10-C程序的3位数组

输出:

1 2 3 4 1 2 7 1 3 6 1 4 5 1 9 2 3 5 2 8 3 7 4 6 10 

预期产出:

 1 2 7 1 3 6 1 4 5 2 3 5 

我只想要那些总和为10并且也只有3位的数字对,即应该显示总和为10的3个不同数字对,其他所有其他对都跳过或不显示。

下面是我为此问题编写的完整源代码。

 #include  #include  void partition(int part) { int *parts, *ptr, i, idx = 0, tot = 0, cur = 1, max = 1; while ((max * (max + 1)) / 2 <= part) max++;` ptr = parts = malloc(sizeof(int) * max); for (;;) { if ((tot += *ptr++ = cur++) < part) continue; if (tot == part) { for (i = 0; i  part); } } int main(int argc, char*argv[]) { int n; scanf("%d", &n); partition(n); return 0; } 

你的代码似乎太复杂了。 这是一个简单的解决方案:

 #include  #define SUM 10 int main(void) { for(int a = 1; a < SUM; a++) { for(int b = a + 1; b < SUM; b++) { for(int c = b + 1; c < SUM; c++) { if(a + b + c == SUM) { printf("%d %d %d\n", a, b, c); } } } } } 

节目输出:

  1 2 7
 1 3 6
 1 4 5
 2 3 5

这可能更有效,但它是一种简单的forms。

您的代码对于此问题过于通用:您不需要枚举所有可能的分区并选择具有3个数字的分区。 只需枚举所有可能的三元组而不重复。

这是一个更简单,更快速的解决方案:

 #include  void partition(int sum) { /* enumerate a, b, c such that: a < b < c a + b + c = sum */ int a, b; for (a = 1; 3 * a + 2 <= sum; a++) { for (b = a + 1; a + 2 * b + 1 <= sum; b++) { printf("%d %d %d\n", a, b, sum - a - b); } } } int main(void) { int n; if (scanf("%d", &n) == 1) partition(n); return 0; }