user7122335 - 4 months ago 29

C Question

I have a code that finds the sum of the divisors of a number, but I can't get it to apply on my increasing n and print all the numbers respectively.

The code is

`long div(int n) {`

long sum = 0;

int square_root = sqrt(n);

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

if (n % i == 0) {

sum += i;

if (i * i != n) {

sum += n / i;

}

}

}

return sum - n;

}

On my main() I need to have a c number that starts from 1 and goes to my MAXCYC which is 28. The n goes from 2 to MAXNUM which is 10000000. The program needs to find all perfect, amicable and sociable numbers and print them with their respective pairs.

Cycle of length 5: 12496 14288 15472 14536 14264 12496

`for (int n = 2; n <= MAXNUM; n++) {`

long sum = div(n);

long res = div(sum);

if (res <= MAXNUM) { // Checking if the number is just sociable

int c = 0;

while (c <= MAXCYC && n != res) {

res = div(sum);

c++;

}

if (c <= MAXCYC) {

printf("Cycle of length %d: ", c);

printf("%ld ", sum);

do {

printf("%ld ", res);

res = div(res);

}

while (sum < res);

printf("%ld ", sum);

c += c - 2;

printf("\n");

}

}

}

I only get pairs of cycle length of 1, 2 and nothing above that. Also it doesn't even print it correctly since it says Cycle of length 0: in all of the results without increasing. I think the problem is in the

What do you guys think I should change?

Answer

Ok, this code should work if I understood well your requirement.

```
#include <stdio.h>
#include <stdlib.h>
int div_sum(int n)
{
long sum = 0;
int square_root = sqrt(n);
for (int i = 1; i <= square_root; i++)
{
if (n % i == 0)
{
sum += i;
if (i * i != n)
{
sum += n / i;
}
}
}
return sum - n;
}
int MAX_N = 10000000;
int MAX_CYCLES = 28;
int main()
{
int cycles;
for(int n = 2; n < MAX_N; n++){
int found = 0;
for(int c = 1; !found && c <= MAX_CYCLES; c++){
cycles = c;
int aliquote = n;
while(cycles--) aliquote = div_sum(aliquote);
//it is a cycle of length c
cycles = c;
if(n == aliquote){
printf("Cycle of length %d: %d", c, n);
while(cycles--){
aliquote = div_sum(aliquote);
printf(" %d", aliquote);
}
printf("\n");
found = 1;
}
}
}
return 0;
}
```