Skip to content

Instantly share code, notes, and snippets.

@margusmartsepp
Created July 30, 2011 23:29
Show Gist options
  • Select an option

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

Select an option

Save margusmartsepp/1116149 to your computer and use it in GitHub Desktop.
fibonacci
/**
* 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];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment