Search code examples
pythonc++bigintegerfactoriallogarithm

big integer calculation in c++ using logarithms


I am reading The Algorithm Design Manual by Steven S. Skiena and came across the topic of logarithms. It just hit me that instead of using python for big ints in competitive programming, I could just use the log(.) function in !(at least wherever I can). I coded a couple of programs to calculate the product of some big integers(20 digits) and factorial of a number(I tried 30! -> 32 digits), and guess what, the answers seem to be correct!

Now I want you guys to tell me what all possible problems can I face with this idea?

So often I have seen people using python especially for the purpose of handling big integers without having to use arrays for it. Using log for operations involving large numbers is a very simple idea but is still not widely being applied for this purpose AFAIK. So if someone else has previously thought of it and tried implementing it, they could tell me about the issues I could potentially face.

For finding factorial, my code was :

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main() {
int i = 30;
long double s = 0;
for (int j = 1; j <= i; ++j)
    s += log(j);
cout << setprecision(300) << exp(s) << endl;
    return 0;
}

Solution

  • The log function in cmath is overloaded and has the following prototypes

         double log (double x);
          float log (float x);
    long double log (long double x);
         double log (T x);     // additional overloads for integral types
    

    The log function casts whatever the input to a double and then returns you another double or float or long double.

    You are basically doing calculations with floating point numbers when you use log. This has some problems.

    • If your input number x is larger than what a double or long double can hold, the input cannot be cast properly.
    • If the output is larger that what a double or long double can hold then the output cannot be cast properly
    • Floating point calculations are not exact. Just try doing 0.1 + 0.2 == 0.3
    • Your program is limited by floating point precision. You cannot have floating point numbers with infinite precision or numbers greater than 1.8e308

    Even if you are not into number theory kind of calculations and just want to use some large numbers (< 1.8e308) then you are better off using double or long double as the calculations will be significantly faster as compare to using log.

    If you need to use large numbers without losing precision then you will have to use some specialized library such as gmp or use arrays as you said.