I want to find sum of all divisors of a number ie 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++)
将i = i更改为i = 1
int divisorsSum(int n){
int sum=0;
for (int i=1; i<=n; i++){
if(n%i==0)
sum+=i;
}
return sum;
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.