C 中的基本循环 - 如何求因子之和

Basic loops in C - How to find the sum of factors

我的 C 课程已经进行了大约 4 周,并且正在开发一个基本上会输出以下内容的程序 -

 ./perfect
Enter number: 6
The factors of 6 are:
1
2
3
6
Sum of factors = 12
6 is a perfect number

./perfect
Enter number: 1001
The factors of 1001 are:
1
7
11
13
77
91
143
1001
Sum of factors = 1344
1001 is not a perfect number

我目前的工作 -

// Testing if a number is perfect

#include <stdio.h>

int main (void) {

//Define Variables
    int input, sum;
    int n;

//Obtain input
    printf("Enter number: ");
    scanf("%d", &input);

//Print factors
    printf("The factors of %d are:\n", input);

    n = 1;
    while (n <= input) {
        if (input % n == 0) {
            printf("%d\n", n);

        }

        n = n + 1;

    }
    //Sum of factors
    //printf("Sum of factors = %d", sum);

    //Is it a perfect number?
    if (sum - input == input) {
        printf("%d is a perfect number", input);
    } else if (sum - input == !input) {
        printf("%d is not a perfect number", input);

    }

    return 0;
}

所以我已经完成了第一部分和最后一部分(我认为)。它只是总结了我正在努力解决的因素。

如何将所有因素相加?应该放在第一个while循环里,还是单独放?

如有任何帮助,我们将不胜感激!

谢谢!

是的。我会在顶部初始化 sum=0 并添加 sum += n;到第一个 while 循环。这应该适合你。

你可以在第一个循环中完成。例如,

    factorsSum = 0;
    while (n <= input) {
    if (input % n == 0) {
        printf("%d\n", n);
        factorsSum += n;
    }

希望这对您有所帮助 =)

试试这个。

#include <stdio.h>

int main (void) {

//Define Variables
int input, sum;
int n;

//Obtain input
printf("Enter number: ");
scanf("%d", &input);

//Print factors
printf("The factors of %d are:\n", input);

for (n=1, sum=0; n <= input; n++) {
    if (input % n == 0) {
        printf("%d\n", n);
        sum += n;
    }
}
//Sum of factors
//printf("Sum of factors = %d", sum);

//Is it a perfect number?
if ((sum - input) == input) {
    printf("%d is a perfect number", input);
} else {
    printf("%d is not a perfect number", input);
}

return 0;
}
var sum =0;

    for (var i=1, sum=0; i <= input/2; i++) {
           if (input % i == 0) {
               printf("%d\n", n);
               sum += i;
           }    
}    
//Sum of factors    
//printf("Sum of factors = %d", sum);

此代码非常适合您。 循环次数较少 了解更多信息 see here