题解 | #完数VS盈数#

完数VS盈数

https://www.nowcoder.com/practice/ccc3d1e78014486fb7eed3c50e05c99d

// 一个数如果恰好等于它的各因子(该数本身除外)子和,
// 如:6=3+2+1。则称其为“完数”;若因子之和大于该数,则称其为“盈数”。
// 求出2到60之间所有“完数”和“盈数”。
// 并以如下形式输出: E: e1 e2 e3 ......(ei为完数) G: g1 g2 g3 ......(gi为盈数) 其中两个数之间要有空格,行尾不加空格。

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

// 求出所有的因子之和
int divisor(int num) {
    int total = 1;
    for (int i = 2; i < sqrt(num); i++) {
        if (num % i == 0) {
            total += i;
            total += num / i;
        }
    }
    if (sqrt(num) == (int)sqrt(num)) {
        total += sqrt(num);
    }
    return total;
}

int main() {
    int good[60] = {0};
    int bad[60] = {0};
    int goodIndex = 0;
    int badIndex = 0;
    for (int number = 2; number <= 60; number++) {
        int result = divisor(number);
        if (result == number) {
            // 如果是完数
            good[goodIndex++] = number;
        } else if (result > number) {
            // 如果是盈数
            bad[badIndex++] = number;
        }
    }
    // 输出结果
    printf("E:");
    for (int i = 0; good[i] != 0; i++) {
        printf(" %d", good[i]);
    }
    printf("\nG:");
    for (int i = 0; bad[i] != 0; i++) {
        printf(" %d", bad[i]);
    }

    system("pause");
    return 0;
}

全部评论

相关推荐

科大讯飞消费者bg二级研究院 语音算法岗 24k*14
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务