180 likes | 325 Views
Objectives of these slides: illustrate recursion. 2 – Recursion. Recursion . Factorial The Fibonacci Series Depth Tester. Factorial. Mathematical Definition: Factorial n (n!) n! = 1, if n<=1 = n*(n-1)! Otherwise. The C version:.
E N D
Objectives of these slides: illustrate recursion 2 – Recursion
Recursion • Factorial • The Fibonacci Series • Depth Tester
Factorial • Mathematical Definition: Factorial n (n!) n! = 1, if n<=1 = n*(n-1)! Otherwise
The C version: longint factorial(long int n) { if(n<=1) return 1; else return (n * factorial(n-1)); }
#include<stdio.h> long int factorial(long int n); int main() { int i; for(i=1; i<=10; i++) printf(“%ld\n”, factorial(i)); return 0; } long int factorial(long int n) { if(n<=1) return 1; else return (n * factorial(n-1)); } Full program
fact(10) 3628800 fact(9) 362880 fact(8) 40320 fact(1) 1 Recursion Uses Lots of Memory
A Common Error long factorial(long n) { if(n<=1) return 1; else return (n*factorial(--n)); }
The Fibonacci Series 0, 1, 1, 2, 3, 5, 8, 13, 21, … • Mathematical definition: fib n = 0 if n = 0 = 1 if n = 1 = fib(n-1) + fib(n-2) if n > 1
The C version long int fib(long int n) { if(n==0 || n==1) return n; else return fib(n-1) + fib(n-2); }
#include<stdio.h> long int fib(long int n); int main() { long int result, number; printf(“Enter an integer: “); scanf(“%ld”, &number); result = fib(number); printf(“Fibonacci(%ld) = %ld\n”, number, result); return 0; } Full program continued
long int fib(long int n) /*return the nth fibonacci number */ { if(n==0 || n==1) return n; else return fib(n-1) + fib(n-2); }
Executions Enter an integer: 5 Fibonacci(5) = 5 Enter an integer: 20 Fibonacci(20) = 6765
fib(5) fib(4) + fib(3) fib(2) + fib(1) fib(3) + fib(2) fib(1) + fib(0) fib(1) + fib(0) fib(2) + fib(1) 1 fib(1) + fib(0) 0 0 0 1 1 1 1 Recursion can be Inefficient
Depth Tester /* Test the depth of recursion for sum() in steps of 100 */ #include<stdio.h> long int sum(long int n); int main() { long int n=0; for( ; ; n+=100) printf(“Recursion test: n = %ld sum = %ld\n”,n,sum(n)); return 0; }
long int sum(long int n) /*sum the integers between 1 and n */ { if(n<=1) return n; else return n + sum(n-1); }
Results on a PC : :Recursion test: n = 7900 sum = 31208950 Recursion test: n = 8000 sum = 32004000 Recursion test: n = %ld sum = %ld > /* prompt */
sum(8001) ? sum(8000) 32004000 sum(7999) 31996001 sum(7998) 31988003 1 sum(1) Execution Stack
But on a workstation :Recursion test: n = 65100 sum = 2119037550Recursion test: n = 65200 sum = 2125552600Recursion test: n = 65300 sum = 2132077650Recursion test: n = 65400 sum = 2138612700Recursion test: n = 65500 sum = 2145157750Recursion test: n = 65600 sum = -2143254496Recursion test: n = 65700 sum = -2136689446Recursion test: n = 65800 sum = -2130114396Recursion test: n = 65900 sum = -2123529346Recursion test: n = 66000 sum = -2116934296Recursion test: n = 66100 sum = -2110329246 :