Generere potensen av et tall
powfunction 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.
- The base case is when , and .
- If is positive and even, recursively compute , and then . Notice that you can get away with making just one recursive call in this case, computing just once, and then you multiply the result of this recursive call by itself.
- If is positive and odd, recursively compute , so that the exponent either is 0 or is positive and even. Then, .
- If is negative, recursively compute , so that the exponent becomes positive. Then, .