Skip to content

Instantly share code, notes, and snippets.

@TheBlackPlague
Created March 21, 2022 16:00
Show Gist options
  • Save TheBlackPlague/d04979d2afcf01b8ec9e9b508f9e4b8a to your computer and use it in GitHub Desktop.
Save TheBlackPlague/d04979d2afcf01b8ec9e9b508f9e4b8a to your computer and use it in GitHub Desktop.
Some Java code to calculate large fibonacci numbers.
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.math.BigInteger;
public class LargeFibonacci {
public static void main(String[] args) {
BigInteger x = new BigInteger("0");
BigInteger y = new BigInteger("1");
for (int i = 0; i < 1000; i++) {
System.out.println(i + 1 + " => " + formatNumber(y));
BigInteger b = new BigInteger(String.valueOf(y));
y = nextFibonacci(x, y);
x = new BigInteger(String.valueOf(b));
}
}
private static @NotNull String formatNumber(@NotNull BigInteger number) {
String numberString = number.toString();
StringBuilder sb = new StringBuilder();
int i = numberString.length() - 1;
int passed = 0;
while (i >= 0) {
if (passed == 3) {
passed = 0;
sb.append(",");
continue;
}
sb.append(numberString.charAt(i));
i--;
passed++;
}
return sb.reverse().toString();
}
@Contract(pure = true)
private static @NotNull BigInteger nextFibonacci(@NotNull BigInteger one, BigInteger two) {
return one.add(two);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment