Created
July 30, 2011 23:29
-
-
Save margusmartsepp/1116149 to your computer and use it in GitHub Desktop.
fibonacci
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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