习题2.5.1

习题2-1 水仙花数(daffodil)

输出100~999中的所有水仙花数。若3位数ABC满足ABC = A^3 + B^3 + C^3,则称其为水仙花数。例如 153 = 1^3 + 5^3 + 3^3,所以153是水仙花数。

c:

#include <stdio.h>
#include <math.h>

int main() {

    int b, s, g;

    for (int i = 100; i < 1000; ++i) {
        b = i / 100;
        s = (i / 10) % 10;
        g = i % 10;

        if (i == (pow(b, 3) + pow(s, 3) + pow(g, 3))) {
            printf("%d\n", i);
        }
    }

    return 0;
}

习题2-2 韩信点兵(hanxin)

相传韩信才智过人,从不直接清点自己军队的人数,只要让士兵先后以三人一排、五人一排、七人一排地变换队形,而他每次只掠一眼队伍的排尾就知道总人数了。输入包含多组数据,每组数据包含3个非负整数a,b,c,表示每种队形排尾的人数(a<3, b<5, c<7),输出总人数的最小值(或报告无解)。已知总人数不小于10,不超过100。输入到文件结束为止。
样例输入:
2 1 6
2 1 3
样例输出:
Case 1:41
Case 2:No answer

c:

#include <stdio.h>

int main() {

        FILE *fin = NULL, *fout = NULL;

        fin = fopen("data.in", "rb");
        fout = fopen("data.out", "wb");

        int sum, a, b, c, min, idx = 1;

        while (fscanf(fin, "%d%d%d", &a, &b, &c) == 3) {
                /*
                 *  sum = 3 * x1 + a;
                 *  sum = 5 * x2 + b;
                 *  sum = 7 * x3 + c;
                 */
                min = -1;
                if (a < 3 && b < 5 && c < 7) {
                        for (sum = 10; sum <= 100; ++sum) {
                                if ((sum - a) % 3 == 0 && (sum - b) % 5 == 0
                                    && (sum - c) % 7 == 0) {
                                        min = sum;
                                        break;
                                }
                        }
                } else {
                        fprintf(fout, "Case %d: No answer\n", idx++);
                        continue;
                }
                if (min > 0) {
                        fprintf(fout, "Case %d: %d\n", idx++, min);
                        continue;
                } else {
                        fprintf(fout, "Case %d: No answer\n", idx++);
                        continue;
                }
        }

        fclose(fin);
        fclose(fout);

        return 0;
}
Last modified:7 September 2019