C中的基本循环 - 如何找到因子的总和

时间:2016-04-11 14:15:09

标签: c while-loop sum logic

我进入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循环的一部分,还是单独放置?

非常感谢任何帮助!

谢谢!

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

希望这有助于=)

答案 2 :(得分:0)

试试这个。

#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;
}

答案 3 :(得分: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