Here is O(1) solution :
private static long fibonacci(int n) {
double pha = pow(1 + sqrt(5), n);
double phb = pow(1 - sqrt(5), n);
double div = pow(2, n) * sqrt(5);
return (long) ((pha - phb) / div);
}
Binet's Fibonacci number formula used for above implementation.
For large inputs long
can be replaced with BigDecimal
.