Chapter 3 Discrete Structures
Recursive functions are functions that call themselves using a smaller version of the function values until a halting condition is met.This technique is frequently used to work with problems that can be defined as smaller copies of themselves. For example, when we calculated the gcd, we used a recursive technique: We continually redefined the problem using smaller and smaller numbers until we reached a remainder of zero. The initial problem gcd(r,r-1) was solved as r(n)=q*r(n-1)+r(n-2). Once we got r(n-1) and r(n-2), we redefined the problem as solving for gcd(r-1,r-2). We kept repeating the process until the remainder was 0. At that point we had the gcd. The same idea was used to get the inverse of a mod.
Recursion occurs naturally in such structures as scanning graphs and trees as we will see in chapter 7 and 8 as well as 10.
The recursive relationships can be solved as seen in section 5.2. While many problems can be defined recursively, using recursion in a computer program is more costly that using iteration. However, in some cases, a recursive solution is easier to develop (see chapter 7, 8 and 10).
| Recursive Functions | ||||
| Name | Halting Condition | Recursive Step | Example | Comments |
| Factorial | f(0)=1 | f(n)=n*f(n-1) | f(4)=4*f(3) f(3)=3*f(2) f(2)=2*f(1) f(1)=1*f(0)=1 1*2*3*4 |
Once you get to the bottom, work your way back up with the values in the equation |
| Fibonocci | f(0)=0 f(1)=1 |
f(n)=f(n-1)+f(n-2) | f(4)=f(3)+f(2) f(3)=f(2) +f(1) f(2)=f(1)+f(0) 0+1+2+3+5+8 |
|
| GCD | a=0, gcd(a,b)=b | gcd(a,b)= gcd(b mod a, a) |
gcd (252,198)= gcd(198,54)= gcd(54,36)= gcd(36,18)= gcd(0,18) Note: The algorithm we did in class was recursive-- we brock down the gcd problem in to a smaller version of itself. |
r(1)=q*r(2)+r(3) r(2)=q*r(3)+r(4) r(3)=q*r(4)+r(5) until r(n)=0 |
| Pascal's Identity | C(n,0)=1 C(n,n)=1 |
C(n+1,k)=C(n,k-1) + C(n,k) | C(3,2)=C(2,1) + C(2,2) C(2,1)=C(1,0)+C(1,1) |
C(2,2)=1 C(2,1)=1+1=2 C(2,2)=1+2 |
| Sum of the first n integers | a(1)=1 | a(n)=a + a(n-1) | a(3)=3+a(2) a(2)=2+a(1) a(1)=1 |
working backwards we have 1+2+3 |
| Interest | P(0)=initial amount, r=rate | P(n)=r*P(n-1) | P(1)=1.1*P(2) P(2)=1.1*P(1) |
You end up with P(n+1)=rnP(0) |
You are the visitor to this site.