0

I have a number 'x' raised to 'n', and I want to calculate the x^n without x.x.x.x....(n times). How do I do that? Is it possible to do it without the tedious self-multiplication?

(I mean to do it without computers)

I've been suggested using logarithms, but how efficient are they and do they have a limit?

Thanks!

  • Use logarithms and exponentiation – Claude Leibovici Jun 28 '21 at 13:53
  • $x^n= \exp(n\log_e(x))$ if $x>0$. Or the old fashioned way using tables which avoids even a single multiplication: $10\hat{}(10\hat{}(\log_{10}(n)+\log_{10}(\log_{10}(x))))$ if $x>1$ – Henry Jun 28 '21 at 14:15
  • 1
    What do you mean by "calculate"? I guess you mean calculate with pencil and paper, since most calculators and computer algebra systems (even typing into google) allow for exponentiations to be calculated without repeated multiplication (by the user). Here's one way: Say you want to calculate $5^{14}$ (in the sense of obtaining a base-10 numeral for the value). Squaring $5$ successively gives $5^2,$ $5^4,$ $5^8.$ Now multiply $5^4$ and $5^8$ together to get $5^{12},$ a process that involves a total of $4$ multiplications (two of which are a bit lengthy). – Dave L. Renfro Jun 28 '21 at 14:29

2 Answers2

0

This can be achieved in O(lg(n)) time:

    double exponent(double x, uint32_t n)  {
        double result = 1.0;
        while (n > 0u)
        {
           if ((n % 2) == 1)
           {
              result *= x;
              n--;
           }
          n = n / 2;
          x = x * x;
        }
        return result;
    }
0

Here's @Vectorizer 's $O(\log n)$ solution as a recursive function. $$\mathrm{pow}(x,n) = \begin{cases} x & \textrm{, if } n=1\\ \mathrm{pow}\left(x^2,\dfrac{n}{2}\right) & \textrm{, if } n \textrm{ is even}\\ x\cdot \mathrm{pow}\left(x^2,\dfrac{n-1}{2}\right) & \textrm{, if } n \textrm{ is odd} \end{cases}$$