Skip to content

Instantly share code, notes, and snippets.

@onacit
Last active November 30, 2018 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onacit/20c6d4561a7369413a039b1b004cd1fc to your computer and use it in GitHub Desktop.
Save onacit/20c6d4561a7369413a039b1b004cd1fc to your computer and use it in GitHub Desktop.
Get fibonacci number of given nth term.
import java.math.BigInteger;
public class Fibonacci {
public static void main(final String... args) {
final int n = Integer.parseInt(args[0]);
if (n < 0) {
throw new IllegalArgumentException("n(" + n + ") is negative");
}
if (n == 0) {
System.out.println(0);
return;
}
if (n == 1) {
System.out.println(1);
return;
}
final BigInteger[] a = new BigInteger[]{BigInteger.ZERO, BigInteger.ONE};
BigInteger o;
for (int i = 2; i <= n; i++) {
o = a[0];
a[0] = a[1];
a[1] = a[1].add(o);
}
System.out.println(a[1].toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment