Skip to content

Instantly share code, notes, and snippets.

@lotabout
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lotabout/9678241 to your computer and use it in GitHub Desktop.
Save lotabout/9678241 to your computer and use it in GitHub Desktop.
compute the fact fo a very large number.
#include <stdio.h>
int multi(char *a, int len, int b)
{
int i;
int carry = 0;
for (i = 0; i < len; i++) {
int tmp = (a[i] - '0') * b + carry;
a[i] = tmp % 10 + '0';
carry = tmp / 10;
}
while (carry != 0) {
a[len] = carry % 10 + '0';
carry /= 10;
len += 1;
}
return len;
}
void swap(char *array, int a, int b)
{
char tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
void reverse(char *array, int len)
{
int i;
int mid = len / 2;
for (i = 0; i < mid; i++) {
swap(array, i, len-1 - i);
}
}
void CalcNN(int n, char *pOut)
{
int i;
int len = 1;
pOut[0] = '1';
for (i = 1; i <= n; i++) {
len = multi(pOut, len, i);
}
reverse(pOut, len);
pOut[len] = '\0';
}
int main(int argc, const char *argv[])
{
char buf[BUFSIZ];
int num;
scanf("%d", &num);
CalcNN(num, buf);
printf("result: %s\n", buf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment