50 likes | 216 Views
Fibonacci. Here is the rule for filling the chart: fib( N ) = fib( N-1 ) + fib( N-2 ) Look at the chart to verify that the rule works. Example. Write a recursive method that has one parameter n of type int and that returns the nth Fibonacci number.
E N D
Fibonacci Here is the rule for filling the chart: fib( N ) = fib( N-1 ) + fib( N-2 ) Look at the chart to verify that the rule works. Simab Shahid UOH, Girls Branch
Example • Write a recursive method that has one parameter n of type int and that returns the nth Fibonacci number. • The Fibonacci numbers are F0 is 0,F1 is 1,F2 is 1,F3 is 2 and in general Fn=Fn-1+fn-2 ,f0=0, F1=1. • Call the method in Test class that has the main method to print the Fibonacci for numbers “1 to 10” using for loop. • Base Step: • Fib (n)=n if n=0 or 1 • Recursive Step: • Fib(n)=Fib(n-2)+Fib(n-1), Simab Shahid UOH, Girls Branch
class Fib { public static int Fib( int n ) { if (n<2 ) return n; else return (Fib(n-2)+Fib(n-1)); } Public static void main( String[] args){ { for ( int i = 0; i < 11; i ++) { System.out.println(i + "th Fibonacci number:of " + i + " is “+Fib( i )); } } } Simab Shahid UOH, Girls Branch
Output: 0th Fibonacci number of 0 is 0 1th Fibonacci number of 1 is 1 2th Fibonacci number of 2 is 1 3th Fibonacci number of 3 is 2 4th Fibonacci number of 4 is 3 5th Fibonacci number of 5 is 5 6th Fibonacci number of 6 is 8 7th Fibonacci number of 7 is 13 8th Fibonacci number of 8is 21 9th Fibonacci number of 9is34 Simab Shahid UOH, Girls Branch