Skip to content

Instantly share code, notes, and snippets.

@margusmartsepp
Created July 31, 2011 00:11
Show Gist options
  • Select an option

  • Save margusmartsepp/1116172 to your computer and use it in GitHub Desktop.

Select an option

Save margusmartsepp/1116172 to your computer and use it in GitHub Desktop.
fibonacci
/// <summary>
/// Gives the Fibonacci number.
/// </summary>
/// <remarks>using System.Numerics;</remarks>
/// <param name="n">element to return.</param>
/// <returns>Fibonacci and Negafibonacci numbers.</returns>
public static BigInteger fibonacci(int n)
{
if (n == 0)
return BigInteger.Zero;
int an = Math.Abs(n);
int nr = 2;
BigInteger[] result = { BigInteger.One, BigInteger.One };
BigInteger[] tmp = new BigInteger[nr];
for (int i = 1; i < an; i++)
{
tmp[0] = BigInteger.Add(result[0], result[1]);
tmp[1] = result[0];
Array.Copy(tmp, 0, result, 0, 2);
}
return ((n < 0) && (n % 2 == 0)) ? -result[1] : result[1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment