DamagedSoul97
DamagedSoul97

Reputation: 33

C Programming: How to add up divisors of an integer n

I was wondering, how can I add up the divisors displayed once I run my code?

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int n, i;
    scanf("%d", &n);

    for(i = 1; i < n; i++)
    {
        if(n % i == 0)
        {
            printf("%d\n", i);
        }
    }
    return 0;
}

If I were to enter, say, 25, it would print out 1, 5. I was wondering how to add up the two numbers 1 and 5?

Upvotes: 0

Views: 956

Answers (2)

chux
chux

Reputation: 153417

How to add up divisors of an integer n?

Iterating n times as with for(i = 1; i < n; i++) can take a long time when n is some high value, especially if code used 64-bit integers. Instead only iterate sqrt(n) times - much faster

int factor_count(int number) {
  if (number <= 1) {
    return TBD_Code(number);  // OP needs to define functionality for these cases.
  }
  int sum = 1;
  int quotient;   
  int divisor = 1;
  do {
    divisor++;
    quotient = number/divisor;
    int remainder = number%divisor;
    if (remainder == 0) {
      sum += divisor;
      if (quotient > divisor) sum += quotient;
    }
  } while (divisor < quotient);
  return sum;
}

Additional improvements noted here.

Upvotes: 2

Tanner Babcock
Tanner Babcock

Reputation: 3350

Could it be as simple as this? You will want to use a simple increment operator (+=), to increment the variable sum.

int main(void)
{
    int n, i, sum = 0;
    if( scanf("%d", &n)!= 1){
        fprintf(stderr,"Error in input\n");
        exit(EXIT_FAILURE);
    }

    for(i = 1; i < n; i++)
    {
        if(n % i == 0)
        {
            printf("%d\n", i);
            sum += i;
        }
    }
    printf("Sum of divisors: %d\n", sum);
    return 0;
}

Upvotes: 5

Related Questions