Pages

Saturday, July 30, 2011

Fibonacci numbers

Mathematica
Note, that this implementation exists. Algorithm is:
Fibonacci[n_] := Round[GoldenRatio^n/Sqrt[5]]

Be aware, that this formula:
can not be trivially applied in other languages.

Java
In Java, we have arbitrarily large integers and decimals, but prebuilt classes lack the functionality (it's a shame). For example we can not easily take root of 5. To do this, we would need to use a library like JScience or write Newton approximation method (what can be quite error prone process).

/**
* Gives the Fibonacci number.
*
* @param n
* element to return.
* @return Fibonacci and Negafibonacci numbers.
*/
public static BigInteger fibonacci(final int n) {
if (n == 0)
return BigInteger.ZERO;
int an = Math.abs(n);
BigInteger[] result = { BigInteger.ONE, BigInteger.ONE };
BigInteger[] tmp = new BigInteger[2];
for (int i = 1; i < an; i++) {
tmp[0] = result[0].add(result[1]);
tmp[1] = result[0];
result = Arrays.copyOf(tmp, tmp.length);
}
return ((n < 0) && (n % 2 == 0)) ? result[1].negate() : result[1];
}
view raw gistfile1.java hosted with ❤ by GitHub

C#
In C#, there is no arbitrarily large decimals. It does have class decimal (with 28-29 significant digits), but assuming that Math class supports it, is just asking too much (it's a shame). But thumbs up, for it at least has BigInteger.

/// <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];
}
view raw gistfile1.cs hosted with ❤ by GitHub

No comments:

Post a Comment