Skip to content

Instantly share code, notes, and snippets.

@tombowers
Last active August 29, 2015 14:27
Show Gist options
  • Save tombowers/bfb0d49fbf5ce203d507 to your computer and use it in GitHub Desktop.
Save tombowers/bfb0d49fbf5ce203d507 to your computer and use it in GitHub Desktop.
public long FibonacciNumber(long n)
{
if (n > 92)
throw new ArgumentOutOfRangeException("n", "Fib(>92) will cause a 64-bit integer overflow.");
if (n < -92)
throw new ArgumentOutOfRangeException("n", "Fib(<-92) will cause a 64-bit integer overflow.");
var sqrt5 = Math.Sqrt(5);
var bigPhi = (sqrt5 + 1) / 2;
var miniPhi = bigPhi - 1;
return Convert.ToInt64((Math.Pow(bigPhi, n) - Math.Pow(-miniPhi, n)) / sqrt5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment