Friday, May 15, 2009

TTMath - a bignum library for C++

Came across this handy BigNum library for arbitraily large numbers in C++. All you need to do is include a single header and then declare a bignum type such as:
typedef ttmath::UInt<100> BigInt;
which creates a type that can hold unsigned integers between 0 and 2 ^ (32*100)-1. Which is absolutely huge. Actually you can go even bigger if the stack size on your OS permits. Yes, this library uses the stack for all calculations, there are no dynamic allocations. So now you can define a factorial function like so
BigInt factorial(BigInt n)
{
    if (n == 1 || n == 0)
        return 1;
    n *= factorial(n-1);
    return n;
}
and display all those fun factorials that we love so much. Did you know 35! = 10333147966386144929666651337523200000000 Fascinating eh!

No comments:

Post a Comment