Professional Documents
Culture Documents
Recursive process:
Ingredients for recursion:
1. Base Case
- Does involve a recursive call! Has trivial answer
2. Recursive Step
- Connects solution to its subproblem!
Fibonacci in
Math vs in
Python
Recursion
Tree
Mutual
Recursion
ping(6)
- Examples:
Some
common
Functions
Finding Order ● Take the largest term & drop the constants
of Growth for
expressions
Greatest ● QN: The GCD of two numbers 𝑎 and 𝑏, is the largest positive integer that divides both 𝑎
Common and without remainder
Divisor ● Naive Solution
Example 1. Set GCD to 1
2. Start with 1
3. Check for every number if it divides and b. If it does set it as GCD
4. Continue until you reach a or b
5. Order of Growth: O(min(a, b))
● Euclid’s Algorithm
- Given two numbers a and b, where 𝑎 = 𝑏𝑄 + 𝑟 (the remainder of the division). Then we
have,
● Rules:
- Can only put one disc at a time 2.
- Cannot put larger disc over a smaller disc
● Claim: We can move 3 discs from A to B. Why?
● How to move 4 discs?
- Move 3 discs from A to B
- Move 1 disc from A to C
● Recursion: To move n discs from A to C (viaB):
- Move n-1 discs from A to B (via C)
- Move the disc from A to C
- Move n-1 discs from B to C (via A)
Exponentiation
Example
Fast
Exponentiation
b) Recursive Factorial
Space a) Iterative Factorial
Complexity
Count by
variables and
functions
computed
Let S(n) denote the space needed for factorial w.r.t the input n. S(n) = 3 * const(variables)S
*number of variables are dependent on n
CONCLUDE
Summary ● Recursion
- Solve the problem for a simple (base) case - Express (divide) a problem into one or more
smaller similar problems
● Iteration
- while and for loops
● Order of Growth
- Time and space requirements for computations w.r.t the input
- Different ways of performing a computation (algorithms) can consume dramatically
different amounts of resources.