python - big integer calculation in c++ using logarithms -


i reading algorithm design manual steven s. skiena , came across topic of logarithms. hit me instead of using python big ints in competitive programming, use log(.) function in !(at least wherever can). coded couple of programs calculate product of big integers(20 digits) , factorial of number(i tried 30! -> 32 digits), , guess what, answers seem correct!

now want guys tell me possible problems can face idea?

so have seen people using python purpose of handling big integers without having use arrays it. using log operations involving large numbers simple idea still not being applied purpose afaik. if else has thought of , tried implementing it, tell me issues potentially face.

for finding factorial, code :

#include <iostream> #include <cmath> #include <iomanip> using namespace std;  int main() { int = 30; long double s = 0; (int j = 1; j <= i; ++j)     s += log(j); cout << setprecision(300) << exp(s) << endl;     return 0; } 

the log function in cmath overloaded , has following prototypes

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

the log function casts whatever input double , returns double or float or long double.

you doing calculations floating point numbers when use log. has problems.

  • if input number x larger double or long double can hold, input cannot cast properly.
  • if output larger double or long double can hold output cannot cast properly
  • floating point calculations not exact. try doing 0.1 + 0.2 == 0.3
  • your program limited floating point precision. cannot have floating point numbers infinite precision or numbers greater 1.8e308

even if not number theory kind of calculations , want use large numbers (< 1.8e308) better off using double or long double calculations faster compare using log.

if need use large numbers without losing precision have use specialized library such gmp or use arrays said.


Comments