Professional Documents
Culture Documents
Gongjun Yan
RECURSION
(TEXTBOOK: §4.3, §4.4)
2008/10/29
§4.3: Recursive Definitions
2
Basis Clause: 0 EI
Inductive Clause: For any element x in EI, x + 2,
and x - 2 are in EI.
Extremal Clause: Nothing is in EI unless it is
obtained from the Basis and Inductive Clauses.
29 October 2008
Tips
5
29 October 2008
generalized union
6
29 October 2008
Examples
10
29 October 2008
The Fibonacci Series
12
0
1 1
2 3
58
13
2008/10/29
Tree Structures --- Rooted Trees
13
2008/10/29
Examples of Rooted Trees
14
2008/10/29
Tree Structures --- Binary Trees
15
2008/10/29
Example of Extended Binary Trees
16
2008/10/29
Recursive Algorithms (§4.4)
17
2008/10/29
Efficiency of Recursive Algorithms
18
2008/10/29
Modular Exponentiation
19
Alg. #1
Uses the fact that bn = b·bn−1 and that
x·y mod m = x·(y mod m) mod m.
(Prove the latter theorem at home.)
procedure mpower(b≥1,n≥0,m>b N)
{Returns bn mod m.}
if n=0 then return 1 else
return (b·mpower(b,n−1,m)) mod m
Note this algorithm takes Θ(n) steps!
2008/10/29
Modular Exponentiation
20
Alg. #2
Uses the fact that b2k = bk·2 = (bk)2.
procedure mpower(b,n,m) {same signature}
if n=0 then return 1
else if 2|n then
return mpower(b,n/2,m)2 mod m
else return (mpower(b,n−1,m)·b) mod m
What is its time complexity?
Θ(log n) steps
2008/10/29
A Slight Variation
21
2008/10/29
Recursive Euclid’s Algorithm
22
2008/10/29
Sequential Search
23
2 n if m 0
0 if m 1 and n 0
Am.n
2 if m 1 and n 1
Am 1, A(m, n 1)
if m 1 and n 2
2008/10/29
Game Time
25
Game Time
29 October 2008