0

How can I handle large numbers in C?

#include <stdio.h>

unsigned int fb(int val)
{
   if(val == 1)
      return 1;
   val = val * fb(val-1);
}


int main(int argc, char *argv[])
{
 unsigned int rc;
  rc = fb(100);
  printf("return fib is %lu\r\n", rc);
  return 0;
}

If C is not a suitable language then what language people do use to handle such large numbers? I am sure using C will have a benefits like timing, performance.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
dexterous
  • 6,422
  • 12
  • 51
  • 99
  • Implement BigInteger – Ryan Feb 09 '16 at 01:43
  • 1
    100 levels of recursion is probably too many. More than any *real* code should use anyway. You'll want to rewrite this to be not recursive. Also, there are a ton of "bignum" libraries out there. It's your job, not ours, to decide which one is right for your application. – Jonathon Reinhart Feb 09 '16 at 01:43
  • Related to Jonathon's comment, your code appears to use recursion to do this calculation (though there's a syntax error). That can add up to a lot of stack space really quickly, and that can cause problems on some systems. There is an optimization, Tail Call Optimization, which C doesn't require, but many compilers support. It would be useful to learn. In the mean time, consider converting the code to iteration rather than recursion. It wont solve the need for BigInt, but it will avoid stack exploisions. – Cort Ammon Feb 09 '16 at 01:46
  • Also try http://stackoverflow.com/questions/619764/what-is-the-best-way-to-represent-arbitrarily-big-numbers-in-c?rq=1 , which is another duplicate – Cort Ammon Feb 09 '16 at 01:46
  • Hmmm, `fb(int val)` looks more like factorial then "fib". – chux - Reinstate Monica Feb 09 '16 at 03:40

0 Answers0