divisor problems

why it’s giving wrong answer…#include<stdio.h>
#include<math.h>
int main()
{
int i;
long int n,t,sum;
scanf("%ld",&t);
while(t–)
{
sum=0;
scanf("%ld",&n);
for(i=2;i<=sqrt(n);i++)
{
if(n%i==0)
{
if(i==n/i)
sum+=i;
else
sum+=i+(n/i);
}
}
sum+=1;
printf("%ld",sum);
}
return 0;
}

This loop is not correct: for(i=2;i<=sqrt(n);i++)

it should have been for(i=1;i<=n/2;i++)

Check the input example: number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation is: 1 + 2 + 4 + 5 + 10 = 22. for more clarification!

3 Likes

@alpit_93 I don’t know why you have complicated such a simple problem…think simple… proper divisors are upto n/2

  1. correct the loop;…
  2. simple if(n%i==0) sum+=i;
    this will do the task

    btw happy coding enjoy

`

1 Like

Initialize sum=1 and do the sum=sum-n at printf and use ‘\n’ to break the line.

2 Likes

If you want the sum of proper divisors, then set sum = 1 and start loop at i = 2.

If you want the sum of all divisors, then set sum = 0 and start the loop at i = 1.

Looks like, you have mixed up these two.

And may be, your printf prints the answer to all test cases in a single line, whereas the question demands the answers to each test case on a separate line. Try changing your printf to printf("%ld\n",sum); and check whether, that accepts your answer.

//