Skip to content

Instantly share code, notes, and snippets.

@rainiera
Created September 3, 2015 03:15
Show Gist options
  • Save rainiera/e1b7c129a3cd40cdebcf to your computer and use it in GitHub Desktop.
Save rainiera/e1b7c129a3cd40cdebcf to your computer and use it in GitHub Desktop.
Rad factorial algorithm
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int factorial(int n) {
int ans[200]; // answer can have a max of 200 digits.
int temp, // <- carry
m, // <- ones place of the prod, to put in the array
prod, // product of the current digit
i, j; // some counters
ans[0] = 1; // the first digit
m = 1; // digit counter
temp = 0;
for (i = 1; i <= n; i++) {
for (j = 0; j < m; j++) {
prod = (ans[j] * i) + temp; // the product per digit * digit
ans[j] = prod % 10; // the digit in j
temp = prod / 10; // the carry value
}
while (temp != 0) { // the carry value on the array
ans[m] = temp % 10; // the digit to put in the array
temp = temp / 10; // new temp (if any)
m++; // increment the digit counter
}
}
for (i = m-1; i >= 0; i--){ // print the answer
printf("%d", ans[i]);
}
printf("\n");
return 0;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Error: please supply an integer on the command line.\n");
printf("%s\n", strerror(1));
return 1;
} else {
factorial(atoi(argv[1]));
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment