当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Sum of all integer divisors of a number

问题描述:

I want to find sum of all divisors of a number i.e. if the number is 6 i want to have 1+2+3+6=12. My attempt to approach it is:

#include <iostream>

using namespace std;

int divisorsSum(int n){

int sum=0;

for (int i=1; i<=n; i++){

if(n%i==0)

i=sum+i;

}

return sum;

}

int main()

{

cout<<divisorsSum(6);

}

However surprisingly it does not work at all, it returns nothing and i am not able to figure out what is wrong with my code.

Thus the question is how to make it works?

BTW: There is no point in immediately down voting everything I am not an expert and yes i do make mistakes.

网友答案:

You have several issues in your code.

int i = i;

and i is still not defined. You probably wanted i = 1

i = sum + i;

sum is not updated above. You probably wanted sum += i

网友答案:

You need to change your function divisorsSum to use the following code:

int divisorsSum(int n)
{
    int sum = 0;
    for (int i = 1; i <= n; i++)
    {
        if(n % i == 0)
        sum += i;
    }
    return sum;
 }
网友答案:
for (int i=i; i<=n; i++)

Change the i=i to i = 1

网友答案:
int divisorsSum(int n){
    int sum=0;
    for (int i=1; i<=n; i++){
         if(n%i==0)
            sum+=i;

    }
return sum;
}
  1. i starts from 1 and not i
  2. sum+=i and not i=sum+i
网友答案:

Maybe there are better algorithms of finding divisors of a number, but here is the correct version of your code.

int divisorsSum(int n){
    int sum=0;
    for (int i = 1; i <= n; ++i){
       if(n % i == 0)
            sum += i;

    }
    return sum;
}

And here is a little optimized version, if a i is bigger than half of n then i cannot be a divisor of n.

int divisorsSum(int n) {
    int sum=0;
    for (int i = n / 2; i >= 1; --i){
       if(n % i == 0)
            sum += i;

    }
    return sum;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: