1 import java.util.Scanner;
2
3 public class ImprovedFibonacci {
4
5 public static void main(String[] args) {
6
7 Scanner input = new Scanner(System.in);
8 System.out.print("Enter an index for the Fibonacci number: ");
9 int index = input.nextInt();
10
11
12 System.out.println(
13 "Fibonacci number at index " + index + " is " + fib(index));
14 }
15
16
17 public static long fib(long n) {
18 long f0 = 0;
19 long f1 = 1;
20 long f2 = 1;
21
22 if (n == 0)
23 return f0;
24 else if (n == 1)
25 return f1;
26 else if (n == 2)
27 return f2;
28
29 for (int i = 3; i <= n; i++) {
30 f0 = f1;
31 f1 = f2;
32 f2 = f0 + f1;
33 }
34
35 return f2;
36 }
37 }