1 / 4

Fibonacci

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.

Download Presentation

Fibonacci

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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

  3. 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

  4. 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

More Related