CS 202 Computer Science II Lab Fall 2009 October 29.
-
date post
21-Dec-2015 -
Category
Documents
-
view
219 -
download
2
Transcript of CS 202 Computer Science II Lab Fall 2009 October 29.
CS 202Computer Science II Lab
Fall 2009 October 29
Today Topics
• Makefile• Recursion
Makefile
main.out: main.o stack$(VAL).o g++ -o main.out main.o stack$(VAL).o
main.o: main.cpp stack$(VAL).hg++ -c main.cpp
Stack$(VAL).o: stack$(VAL).cpp stack$(VAL).hg++ -c stack$(VAL).cpp
$ make VAL=1
$ make VAL=2
Recursion
• Recursion– A method of specifying a process by means of itself.
• Recursive Function– A way of defining a function using recursion.
• ExampleF(x) = 30x + 7 Direct Implementation
F(x) = F(x-1) - 30 Recursion Implementation
Recursion
• Base Case of a Recursively Defined Function– A value or values for which the recursive function is
concretely defined.
x F(x)
0 7
1 37
2 67
3 97
F(x) = 30x + 7
Base case: F(0) = 7
Recursion
• Recursive Algorithm: – An algorithm that calls itself with smaller and
smaller subsets of the original input, doing a little bit or work each time, until it reaches the base case.
int F(int x){ if (x=0) return 7; else return F(x-1) + 30;}
int F(int x){ return (x= =0) ? 7 : F(x-1)+30;}
Recursion Example
• factorial(n) n! = nx(n-1)x(n-2)x…x2x1 Direct Imp.
n! = nx(n-1)! Recursive Imp.
Base case: If n = 0 then factorial(n) = 1
int factorial(int n){ if (n>0) return n*factorial(n-1); else return 1;}
int factorial(int n){ return (n) ? n*factorial(n-1) : 1; }
Recursion Example• Fibonacci numbers
• A sequence of numbers named after Leonardo of Pisa, known as Fibonacci.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 …
If n = 0 then fib(n) = 1
If n = 1 then fib(n) = 1
If n > 1 then fib(n) = fib(n - 1) + fib(n - 2)
Recursion Example• Fibonacci numbers
int fib(int n){ if (n==0 or n==1) { return 1; } else { return fib(n-1)+fib(n-2); }}
Recursion Example
• The greatest common divisor (GCD) of two integers m and n
int tryDivisor(int m, int n, int g){
if ( ( (m % g) == 0 ) && ( (n % g) == 0 ) )
return g;
else
return tryDivisor(m, n, g - 1);
}
int gcd(int m, int n) {
return tryDivisor(m, n, n); //use n as our first guess
}
gcd(6, 4)
tryDivisor(6, 4, 4)
tryDivisor(6, 4, 3)
tryDivisor(6, 4, 2)
=> 2
GCD
int gcd(int m, int n) {
if(m == n)
return m;
elseif (m > n)
return gcd(m-n, n);
else
return gcd(m, n-m);
}
gcd(468, 24)
gcd(444, 24)
gcd(420, 24)
...
gcd(36, 24)
gcd(12, 24) (Now n is bigger)
gcd(12, 12) (Same)
=> 12
Extremely Smart way to compute GCD
int gcd(int m, int n)
{
if ( (m % n) == 0 )
return n;
else
return gcd(n, m % n);
}
gcd(468, 24)
gcd(24, 12)
=> 12
gcd(135, 19)
gcd(19, 2)
gcd(2, 1)
=> 1
Questions?