Search code examples
c++loopsinteger-division

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.


Solution

  • 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