50 likes | 261 Views
CSci 160 Lecture 18. Martin van Bommel. Fibonacci Sequence. Fibonacci investigated how fast rabbits could breed in ideal circumstances Mate at one month, produce pair of rabbits every month from month two on Link on web
E N D
CSci 160Lecture 18 Martin van Bommel
Fibonacci Sequence • Fibonacci investigated how fast rabbits could breed in ideal circumstances • Mate at one month, produce pair of rabbits every month from month two on • Link on web • Fibonacci sequence for number of pairs is 1 1 2 3 5 8 13 21 34 55 ...
Fibonacci Equation • Sequence 1 1 2 3 5 8 ... can be definedFib(1) = 1Fib(2) = 1Fib(n) = Fib(n-1) + Fib(n-2) if n > 2
Recursive Fibonacci long int Fib(int n) { if (n <= 2) return (1); return (Fib(n-1) + Fib(n-2)); } • fibr.c • Number of recursive calls to Fib = Fib(n+1)
Non-recursive Fibonacci long int Fib(int n) { int i, n1 = 1, n2 = 1, f = 1; for (i = 3 ; i <= n; i++) { f = n1 + n2; n1 = n2; n2 = f; } return f; }