Sum of divisors (C)

From LiteratePrograms

Jump to: navigation, search


This implements the sum of divisors function from number theory in C.

Here d is a divisor of n.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
  int d, divisorsum, n;
  divisorsum=0;
  n=atoi(argv[1]);
  for(d=1; d<=n; d++) {
    if(n % d == 0) {
      divisorsum += d;
    }
  }
  printf("%d\n",divisorsum);
  return(0);

For example: Using n=12, we know that the divisors of 12 are: 1,2,3,4,6,12. Therefore

σ(12) = 1 + 2 + 3 + 4 + 6 + 12 = 28

Here are some running examples.

$ sigma 12
28
$ sigma 5040
19344
$ sigma 100
217
Download code
Views