Recursive Functions: Fibonacci Numbers
Recursive Functions: Fibonacci Numbers
Functions
Recursion
Recursive Functions
Fibonacci Numbers
1
1
Growth is exponential: possible to
find r > 1 st. fn ≥ rn−2 .
√
2 Let r = 1+2 5
= 1.62, so that
r2 = r + 1
3 We need to prove that fn ≥ rn−2 .
Recursive Functions
Fibonacci Numbers
Basis: P (1) is true, f1 = 1, since r1−2 = r−1 ≤ 1.
Note, also that as r2−2 = 1 = f2 , P (2) holds.
Induction hypothesis: for a fixed n > 2, P (1), P (2) . . . P (n) are all
true.
Induction step: consider fn+1 = fn−1 + fn−2 .
Using hypothesis fn ≤ rn−2 + rn−3
So, fn ≤ rn−3 (r + 1) = rn−3 .r2 = rn−1 .
Hence P (n + 1) is true.
i f ( n == 1 ) r e t u r n 1 ;
i f ( n == 2 ) r e t u r n 1 ;
r e t u r n f i b ( n−1) + f i b ( n −2);
}
i n t main ( ) {
int n;
p r i n t f (” Enter n : ” ) ;
s c a n f ( ”%d” , &n ) ;
p r i n t f ( ”%d t h f i b o n a c c i number = %d \ ” , n , fib (n ));
}
fib(4) fib(3)
fib(2) fib(1)
i n t main ( ) {
int n;
p r i n t f ( ” E n t e r a +v e n : ” ) ;
s c a n f ( ”%d” , &n ) ;
p r i n t f ( ” f i b (%d ) = %d\n” , n , f i b o ( 1 , 1 , n ) ) ;
}
i f ( n == 0 )
return 1;
t = power ( x , n / 2 ) ;
i f ( n%2 != 0 )
return x ∗ t ∗ t ;
return t ∗ t ;
}
i n t main ( ) {
int n , x ;
p r i n t f ( ” E n t e r x and n : ” ) ;
s c a n f ( ”%d %d” , &x , &n ) ;
p r i n t f ( ” power(%d , %d ) = %d\n” , x , n , power ( x , n ) ) ;
}
R. K. Ghosh (IIT-Kanpur) C Programming February 24, 2011 7/7