1. Fast exponentiation. This is a fast way to raise a number to an integer power. It requires the fewest multiplies, and does not use logarithms.
Fast Exponentiation of integers, raises
n
to the
p
power
(a) Base Case. Ifp= 0: return 1.0.
(b) Odd. Ifpis odd: returnn×fastexp(n, p−1). (c) Even. Ifpis even:
computet←fastexp(n,p
2); returnt×t.
2. Greatest Common Divisor. The greatest common divisor is the largest number which will evenly divide two other numbers. You use this when you reduce fractions. See Greatest Common Divisor for an alternate example of this exercise’s algorithm. This version can be slightly faster than the loop we looked at earlier.
Greatest Common Divisor of two integers,
p
and
q
(a) Base Case. Ifp=q: returnp.(b) p < q. Ifp < q: return GCD(q, p). (c) p > q. Ifp > q: return GCD(p, p−q).
3. Factorial Function. Factorial of a numbern is the number of possible arrangements of 0 throughn things. It is computed as the product of the numbers 1 throughn. That is,1×2×3× · · · ×n. The formal definition is
n! =n×(n−1)×(n−2)× · · · ×1
0! = 1
We touched on this in Computing e. This function definition can simplify the program we wrote for that exercise.
Factorial of an integer,
n
(a) Base Case. Ifn= 0, return 1.(b) Multiply. Ifn >0: returnn×factorial(n−1).
4. Fibonacci Series. Fibonacci numbers have a number of interesting mathematical properties. The ratio of adjacent Fibonacci numbers approximates the golden ratio ((1 +√5)/2, about 1.618), used widely in art and architecture.
The
nth Fibonacci Number,
F
n.
(a) F(0) Case. Ifn= 0: return 0. (b) F(1) Case. Ifn= 1: return 1.(c) F(n) Case. Ifn >1: return F(n−1) +F(n−2).
5. Ackermann’s Function. An especially complex algorithm that computes some really big results. This is a function which is specifically designed to be complex. It cannot easily be rewritten as a simple loop. Further, it produces extremely large results because it describes extremely large exponents.
Ackermann’s Function of two numbers,
m
and
n
(a) Base Case. Ifm= 0: returnn+ 1.(b) N Zero Case. Ifm̸= 0and n= 0: return ackermann(m−1,1).
(c) N Non-Zero Case. Ifm̸= 0and n̸= 0: return ackermann(m−1,ackermann(m, n−1)). Yes, this requires you to compute ackermann(m, n−1) before you can compute ackermann(m−
1,ackermann(m, n−1)).
6. Maximum Value of a Function. Given some integer-valued function f(), we want to know what value ofxhas the largest value forf()in some interval of values. For additional insight, see[Dijkstra76]. Imagine we have an integer function of an integer, call itf(). Here are some examples of this kind of function.
• ‘def f1(x): return x’
• ‘def f2(x): return -5/3*x-3’ • ‘def f3(x): return -5*x*x+2*x-3’
The question we want to answer is what value ofx in some fixed interval returns the largest value for the given function? In the case of the first example, ‘def f1(x): return x’, the largest value off1() in the interval 0≤x <10occurs when xis 9.
What aboutf3()in the range−10≤x <10?
Max of a Function,
F, in the interval
low
to
high
(a) Initialize.x←low;
max←x;
maxF ←F(max).
(b) Loop. Whilelow≤x < high. i. New Max? If F(x)> maxF:
max←x;
maxF ←F(max). ii. Next X. Incrementxby 1.
(c) Return. Returnmaxas the value at which F(x)had the largest value.
7. Integration. This is a simple rectangular rule for finding the area under a curve which is continuous on some closed interval.
We will define some function which we will integrate, call it f(x)(). Here are some examples. • ‘def f1(x): return x*x’
• ‘def f2(x): return 0.5 * x * x’ • ‘def f3(x): return exp( x )’ • ‘def f4(x): return 5 * sin( x )’
When we specifyy =f(x), we are specifying two dimensions. They is given by the function’s values. Thexdimension is given by some interval. If you draw the function’s curve, you put two limits on the xaxis, this is one set of boundaries. The space between the curve and theyaxis is the other boundary. Thexaxis limits areaandb. We subdivide this interval intosrectangles, the width of each ish= b−sa. We take the function’s value at the corner as the average height of the curve over that interval. If the interval is small enough, this is reasonably accurate.
Integrate a Function,
F, in the interval
a
to
b
in
s
steps
(a) Initialize. x←a h← b−a s sum←0.0 (b) Loop. Whilea≤x < b.
i. Update Sum. Incrementsum byF(x)×h. ii. Next X. Incrementx byh.
(c) Return. Returnsum as the area under the curveF()fora≤x < b.
8. Field Bet Results. In the dice game of Craps, the Field bet in craps is a winner when any of the numbers 2, 3, 4, 9, 10, 11 or 12 are rolled. On 2 and 12 it pays 2:1, on any of the other numbers, it pays 1:1.
Define a function ‘win( dice, num, pays)’. If the value ofdiceequalsnum, then the value ofpaysis returned, otherwise 0 is returned. Make the default forpaysa 1, so we don’t have to repeat this value over and over again.
Define a function ‘field( dice )’. This will callwin()7 times: once with each of the values for which the field pays. If the value of dice is a 7, it returns -1 because the bet is a loss. Otherwise it returns 0
It would start with def field( dice ):
win( dice, 2, pays=2 ) win( dice, 3, pays=1 )
...
Create a function ‘roll()’ that creates two dice values from 1 to 6 and returns their sum. The sum of two dice will be a value from 2 to 12.
Create a main program that calls roll() to get a dice value, then callsfield()with the value that is rolled to get the payout amount. Compute the average of several hundred experiments.
9. range() Function Keywords. Does the range function permit keywords for supplying argument
values? What are the keywords?
10. Optional First Argument. Optional parameters must come last, yet range fakes this out by appear- ing to have an optional parameter that comes first. The most common situation is ‘range(5)’ , and having to type ‘range(0,5)’ seems rather silly. In this case, convenience trumps strict adherence to the rules. Is this a good thing? Is strict adherence to the rules more or less important than convenience?