Search code examples
c++largenumberexponentiation

Large exponents in C++


In C++, how can I calculate something like 2009^1389? (That's 2009 raised to the 1389th power, not the bitwise XOR.)


Solution

  • Simple answer: You can't. That is: 2009^1389 is too large a number to fit into any of the numeric types available to you in C. (Strictly, it's possible that you might have million-bit ints or floats or something, since the C language standard is deliberately rather indefinite about these things, but in practice you don't.)

    If what you actually need is the exact integer value, for some number-theoretic purpose: What you need is a library containing stuff for doing arithmetic on very large integers. I recommend GMP (http://gmplib.org). Such a library will define data structures for representing large integers, and functions for operating on them. Read the documentation!

    If what you actually need is an approximation: Perhaps you can work with the logarithms of all the numbers you care about, in which case #include <math.h> and use the fact that log(a^b) = b log a.

    (The former seems more likely given the "acm" tag.)