...

/

Computing powers of a number

Computing powers of a number

We'll cover the following...

Although most languages have a builtin pow function that computes powers of a number, you can write a similar function recursively, and it can be very efficient. The only hitch is that the exponent has to be an integer.

Suppose you want to compute xnx^n, where xx is any real number and nn is any integer. It's easy if nn is 00, since x0=1x^0 = 1 no matter what xx is. That's a good base case.

So now let's see what happens when nn is positive. Let's start by recalling that when you multiply powers of xx, you add the exponents: xa. xb=xa+bx^a . \space x^b = x^{a + b} for any base xx ...