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 :


 /**
 * 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));


    }

}


Output :

8th fibonacci number is : 21

Iterative Code :


/**
 * 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));
    }

}

Output:

8th fibonacci number is : 21

 


No comments:

Post a Comment

t> UA-39527780-1 back to top