E – Compute fibonacci number

For a given positive integer – N, compute Nth fibonacci number.

Input Format

First and only line of input contains a positive number – N.

Constraints

1 <= N <= 20

Output Format

Print the Nth fibonacci number.

InputcopyOutputcopy
43

Explanation 0

The fibonacci series is defined as:
1, 1, 2, 3, 5, 8,……
At 4th position we have 3.

Solutions:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long N = scanner.nextLong();
        long fibN = fibonacci(N);
        System.out.println(fibN);
        scanner.close();
    }
    public static long fibonacci(long N) {
        if (N <= 1) {
            return N;
        }
        long fibPrev = 0;
        long fibCurr = 1;
        for (long i = 2; i <= N; i++) { 
            long fibNext = fibPrev + fibCurr; 
            fibPrev = fibCurr;
            fibCurr = fibNext;
        }
        return fibCurr;
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top