New power function methods: - The old definition work by defining m^0 = 1 and m^(n+1) = m * m^n. This method takes roughly n steps to execute. (see power_1 in DEMO) - Another method takes advantage of the arithmetic property that for n even, m^n = (m*m)^(n/2). This method takes log_2(n) (log base 2 of n) steps to execute. (see power_2 in DEMO) ****Scheme Aside**** One can use the 'time' function in DrScheme to measure the execution time for a particular function with particular arguments. (You must first switch over to advanced language mode to have access) The relevant number here is the cpu time, given in milliseconds. ******************** - Yet another method improves efficiency further. Here, we take advantage of the facts that p = k * m^n ==> p = (k*m)*m^(n-1) for odd n, and p = k * m^n ==> p = k*(m*m)^n/2 for n even. This method still takes roughly log_2(n) steps, but improves prefactors in relative performance. (See power_3 and times_power in DEMO) - Setting the k argument to 1 in the power_3 to times_power reduces the problem to the case of a simple exponentiation. The difference now lies in the fact that k holds the results of the odd multiplications. ****Aside on Naming Conventions**** A function name should give some good indication of purpose. Still, you don't want to it to be too long so as to make typing it a pain. Finding a balance of these things is an art. If you are working in some collaborative setting, where other people will have to read and understand your code, it is better to err on the side of long, descriptive naming. *********************************** Why is times_power better than power_2? - In times_power, the recursive call is the last thing done. When this is the case, it is called a 'tail-recursion'. In Scheme, a tail recursion is equivalent to an iteration (i.e. loop). - When you implement a tail recursion, there is nothing to keep track of in each recursive call. Each call does its business, and then calls itself. When the last call is made, there is no more work to do except pass the results back up the line. In power_2, the intermediate values of m had to be store in each function to multiply by the successive recursive results. In power_3, this information is instead stored in k and passed down the line to each successive k.