Consider the problem of computing the exponential of a given number. We would like a function that takes as arguments a base b and a positive integer exponent n and computes bnbn. One way to do this is via the recursive definition
    2.8.4   Example: Exponentiation - 图1
    2.8.4   Example: Exponentiation - 图2
    which translates readily into the recursive function

    1. >>> def exp(b, n):
    2. if n == 0:
    3. return 1
    4. return b * exp(b, n-1)

    This is a linear recursive process that requires 2.8.4   Example: Exponentiation - 图3 steps and 2.8.4   Example: Exponentiation - 图4 space. Just as with factorial, we can readily formulate an equivalent linear iteration that requires a similar number of steps but constant space.

    1. >>> def exp_iter(b, n):
    2. result = 1
    3. for _ in range(n):
    4. result = result * b
    5. return result

    We can compute exponentials in fewer steps by using successive squaring. For instance, rather than computing 2.8.4   Example: Exponentiation - 图5as
    2.8.4   Example: Exponentiation - 图6
    we can compute it using three multiplications:
    2.8.4   Example: Exponentiation - 图7
    This method works fine for exponents that are powers of 2. We can also take advantage of successive squaring in computing exponentials in general if we use the recursive rule
    image.png
    We can express this method as a recursive function as well:

    1. >>> def square(x):
    2. return x*x
    3. >>> def fast_exp(b, n):
    4. if n == 0:
    5. return 1
    6. if n % 2 == 0:
    7. return square(fast_exp(b, n//2))
    8. else:
    9. return b * fast_exp(b, n-1)
    10. >>> fast_exp(2, 100)
    11. 1267650600228229401496703205376

    The process evolved by fast_exp grows logarithmically with n in both space and number of steps. To see this, observe that computing 2.8.4   Example: Exponentiation - 图9 using fast_exp requires only one more multiplication than computing 2.8.4   Example: Exponentiation - 图10. The size of the exponent we can compute therefore doubles (approximately) with every new multiplication we are allowed. Thus, the number of multiplications required for an exponent of n grows about as fast as the logarithm of n base 2. The process has 2.8.4   Example: Exponentiation - 图11 growth. The difference between 2.8.4   Example: Exponentiation - 图12 growth and 2.8.4   Example: Exponentiation - 图13 growth becomes striking as nn becomes large. For example, fast_exp for n of 1000 requires only 14 multiplications instead of 1000.