2

how do i store a huge number in a variable (i) and wont need to change much of the program ? Is there a available datatype to store factorial of 100 for example ?

#include<stdio.h>
#include<conio.h>

void main()
{

    long long int i = 1;
    long long int sum = 0;
    long long int j = 0;
    long long int digit = 0;

    for(j = 500; j >= 1; j--)
    {
        i = i * j;

    }
    printf("%lld", i);

    while(i > 0)
    {
        digit = i%10;
        i = i/10;
        sum = sum + digit;
    }

    printf("\n%lld", sum);

    getch();
}
  • You will need to do large number calculation for this. – Jiminion Aug 30 '13 at 15:05
  • 1
    possible duplicate of [Sum of digits of a factorial](http://stackoverflow.com/questions/1469529/sum-of-digits-of-a-factorial) – Eric Postpischil Aug 30 '13 at 15:14
  • 1
    Here is good explanation of one algorithm: http://stackoverflow.com/q/2127540/2186301 Hope, this will help you or bring you some idea ;) – yulian Aug 30 '13 at 16:31
  • A man called Mohammad Shafieenia has written an article "1000 Factorial". Read about the algorhytm and download the source code. I hope that article will help you! Link: http://www.codeproject.com/Articles/38504/1000-Factorial – yulian Aug 30 '13 at 17:03

2 Answers2

1

There is no built-in language support for such large numbers. You have two options:

  • if you can, use existing library, like GMP
  • implement you own solution

If you decide to take the second path, you might want to consider storing digits (not necesserily decimal) in an array, and perform arithmetic operations using well known school algorithms. Keep in mind it will be (probably considerably) less efficient than heavily optimized library code.

Marcin Łoś
  • 3,226
  • 1
  • 19
  • 21
1

@Marcin Łoś is on the money, no C solution without using a library or rolling your own functions.

Follows is a fun, but not imaginative solution where the large number is stored as a array of char (in reverse order).

#include <stdio.h>
#include <string.h>
#include <math.h>

void Mult(char *BigNum, unsigned Factor) {
  unsigned Accumulator = 0;
  char Digit;
  while ((Digit = *BigNum) != '\0') {
    Accumulator += ((unsigned)(Digit - '0')) * Factor;
    *BigNum++ = Accumulator%10 + '0';
    Accumulator /= 10;
  }
  while (Accumulator > 0) {
    *BigNum++ = Accumulator%10 + '0';
    Accumulator /= 10;
  }
  *BigNum = '\0';
}

int main(){
  unsigned N = 500;
  unsigned Factor;
  char BigNum[(size_t) (N*log(N) + 2)];  // Form answer, in reverse order, as a string
  strcpy(BigNum, "1");
  for (Factor = 1; Factor <= N; Factor++) {
    Mult(BigNum, Factor);
  }
  printf("%u! Length:%zu Reverse:\"%s\"\n", Factor - 1, strlen(BigNum), BigNum);
  unsigned long Sum = 0;
  size_t i;
  for (i=0; BigNum[i]; i++) {
    Sum += BigNum[i] - '0';
  }
  printf("Sum of digits:%lu\n", Sum);
  return 0;
}


500! Length:1135 Reverse:"000...221"
Sum of digits:4599
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256