Friday, 6 December 2013

Find nth Fibonacci number in Java?

Fibonacci series is as follows

1 1 2 3 5 8 13 21 34...

You can read more about this sequence in Wiki.

Again for this we can have iterative approach as well as recursive. Recursive code is provided below

Recursive Code :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<b> /**
 * Created with IntelliJ IDEA.
 * User: aniket
 * Date: 6/12/13
 * Time: 3:25 PM
 * To change this template use File | Settings | File Templates.
 */
public class FibonacciFinder {
 
    public static int fibonacci(int number){
 
        if(number <= 2){
            return 1;
        }
        else{
            return  fibonacci(number - 1) + fibonacci(number - 2);
        }
    }
 
    public static void main(String args[]){
 
        System.out.println("8th fibonacci number is : " + fibonacci(8));
 
 
    }
 
}
</b>


Output :

8th fibonacci number is : 21

Iterative Code :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<b>/**
 * Created with IntelliJ IDEA.
 * User: aniket
 * Date: 6/12/13
 * Time: 3:25 PM
 * To change this template use File | Settings | File Templates.
 */
public class FibonacciFinder {
    int prev = 1;
    int curr = 1;
    public int fibonacci(int number){
 
        if(number < 2){
            return curr;
        }
        else {
            int temp;
            for(int i = 0;i<number-2;i++){
                temp = curr;
                curr = curr + prev;
                prev = temp;
            }
            return curr;
        }
    }
 
    public static void main(String args[]){
 
        System.out.println("8th fibonacci number is : " + (new FibonacciFinder()).fibonacci(8));
    }
 
}
</b>

Output:

8th fibonacci number is : 21

 


No comments:

Post a Comment

t> UA-39527780-1 back to top