Divisors (C)

From LiteratePrograms

Jump to: navigation, search


This implements the divisors function from number theory in C. Divisors lists the divisors 'd' of a given number n.

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


Here are some running examples.

$ divisors 12
1, 2, 3, 4, 6, 12
$ divisors 120 
1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120
$ divisors 6
1, 2, 3, 6
$ divisors 5
1, 5
Download code
Views