I'm trying to use the Binet's formula to solve Fibonacci's nth number with an O(1) time complexity.
class Application
{
static void Main(string[] c)
{
Console.WriteLine($"Fib(15) : Expected 610 got : {Fibonacci(15)}");
Console.WriteLine($"Fib(20) : Expected 6765 got : {Fibonacci(20)}");
Console.WriteLine($"Fib(100) : Expected 354224848179261915075 got : {Fibonacci(100)}");
Console.ReadKey();
}
private static BigInteger Fibonacci(int n)
{
double sqrt5 = Math.Sqrt(5d);
return new BigInteger((1/sqrt5)*Math.Pow((1 + sqrt5)/2, n) - (1/sqrt5)*Math.Pow((1 - sqrt5)/2, n));
}
}
The following example works like a charm for the first two tests, but it fails by a quite huge amount for the third test (result is 354224848179263111168
vs. 354224848179261915075
.
I guess it might be a problem with the Math.Pow((1+sqrt5)/2,n)
part of my formula, but I tried using the formula using decimal
, double
, float
and BigInteger
itself, and the result is never the good one.
Is there a way around my problem or should I accept that I can't do this using Math.Pow
?
Edit I tried using BigInteger.Pow
, but to use it 1+sqrt5
needs to be a BigInteger
too, which makes my code look like this at the end because of castings :
double sqrt5 = Math.Sqrt(5d);
return new BigInteger(1/sqrt5)*BigInteger.Pow(new BigInteger(1 + sqrt5/2), n) - new BigInteger(1 / sqrt5) * BigInteger.Pow(new BigInteger((1 - sqrt5)/2), n);
And all values returned are zeroes.