0

使用数字 1 到 9,不重复相同的数字,我制作了这个总和表,其中包括将两个数字加在一起以及每个总和的所有可能组合。我正在尝试用 C 编写一个程序,通过将 2 个数字和它们的每个组合相加来找到所有总和,然后打印出这个图表。我正在尝试使用 for 循环来编写这个程序并且已经卡住了。我可以打印出第一个初始总和,但它正在得到让我现在难倒的组合。我不知道我是否走在正确的轨道上。任何建议和帮助将不胜感激。我的图表,到目前为止编写的代码,以及当前代码的打印输出如下。

这就是我希望我的程序执行的操作:

此图表列出了由 2 位数字组成的所有总和以及构成每个总和的所有可能组合。

    2 Digit Sums
Sum Combinations
3   1+2
4   1+3
5   1+4, 2+3
6   1+5, 2+4
7   1+6, 2+5, 3+4
8   1+7, 2+6, 3+5
9   1+8, 2+7, 3+6, 4+5
10  1+9, 2+8, 3+7, 4+6
11  2+9, 3+8, 4+7, 5+6
12  3+9, 4+8, 5+7
13  4+9, 5+8, 6+7
14  5+9, 6+8
15  6+9, 7+8
16  7+9
17  8+9

这是我能够成功编写的代码:

/* Thus program uses the digits 1 - 9 to find all possible sums composed of two
digits, non repeating, and all possible combinations of digits to obain the sums. */
#include<stdio.h>
int main(void)
{
    int S, A, B;
    A = 1;
    B = A + 1;
    S = A + B;
    printf("\t\t2 Digit Sums\n\n");
    printf("Sum\tCombinations\n");
    for(B; B <= 8; ++B)
    {
        S = A + B;
        printf("%d\t%d + %d\n", S, A, B);
    }
    for(A; (A < B && A !=B); ++A)
    {
        S = A + B;
        printf("%d\t%d + %d\n", S, A, B);
    }       
    return(0);
}

这是我的代码的输出:

                2 Digit Sums
Sum     Combinations
3       1 + 2
4       1 + 3
5       1 + 4
6       1 + 5
7       1 + 6
8       1 + 7
9       1 + 8
10      1 + 9
11      2 + 9
12      3 + 9
13      4 + 9
14      5 + 9
15      6 + 9
16      7 + 9
17      8 + 9
Press any key to continue...
4

1 回答 1

1

如果问题的范围像这样有限,您可以通过蛮力解决它 - 只需尝试一下即可。只有 17 * 9 * 9 种变体可供检查,实际上并不多。

三个循环(伪代码):

for each value of possible_sum (2-17)

    print possible_sum

    for each value of addend1 (1-9)

       for each value of addend2 (1-9) 

       if ( addend1 + addend2 = possible_sum ) 
       then

           print addend1 and addend2

       end if

       end for addend2

    end for addend1

end for possible_sum

留给您的问题是弄清楚如何消除对称解决方案(4+5 和 5+4),如果您查看解决方案中的模式,这很容易(注意第一个加数与第二个加数的关系)。如果你仔细考虑的话,有很多方法可以加速这种蛮力方法。

对于更大的数据集(“所有三位加数......”),将需要更好的算法。

于 2012-11-28T17:18:38.777 回答