Here are three different solutions, it is clear to see which are best. Of course the final looped solution is the best for the problem
big_c is facing.
import java.util.Scanner;
public class FibonacciGenerator
{
public static void main(String[] args){
while(true){
System.out.println("Enter a number to compute the fibonacci number for:");
int n = new Scanner(System.in).nextInt();
System.out.println(fib(n));
System.out.println(fibR(n));
System.out.println(fibL(n));
}
}
public static int fib(double n)
{
return (int)(( Math.pow(((1 + Math.sqrt(5)) / 2 ), n) / Math.sqrt(5) ) + 0.5);
}
public static int fibR(int n){
if(n == 0) return 0;
else if(n <= 2) return 1;
return fibR(n-1)+fibR(n-2);
}
public static int fibL(int n){
int A = 0;
int B = 1;
int current = 0;
if(n == 0) return 0;
else if(n <= 2) return 1;
for(int i = 0; i < n-1; i++){
current = A+B;
A = B;
B = current;
}
return current;
}
}