-1

I want to get the 93rd and more Fibonacci numbers in JAVA. In fact, when I try to get Fibonacci numbers as long, I get at most the 92nd number. Is there any way to reach 93rd and after?

Sample Output

91. number= 4660046610375530309

92. number= 7540113804746346429

93. number= -6246583658587674878

Here is my code:

    long s1 = 0;
    long s2 = 1;
    long current = 0;

    for (int i = 0; i < 100; i++) {
        current = s1 + s2;
        s2 = s1;
        s1 = current;

        System.out.println((i+1) + ". " + current);
    }
Community
  • 1
  • 1

2 Answers2

3

There is a way to reach 93th and after fibonacci numbers. You can use java.math.BigInteger library. You can reach large numbers as you can't imagine like 100.000 digits. Here are the steps:

Add Library

import java.math.BigInteger;

First 10.000 Fibonacci Numbers

BigInteger s1 = BigInteger.ZERO;
BigInteger s2 = BigInteger.ONE;
BigInteger current = BigInteger.ZERO;

for (int i = 0; i < 10000; i++) {
    current = (s1.add(s2));
    s2 = s1;
    s1 = current;
    System.out.println((i+1) + ". " + current);
}
Fatih TAN
  • 778
  • 1
  • 5
  • 23
0

You can use BigInteger. Take a look at this question.

e.g.:

public static BigInteger fib(int n) {
  if (n == 0 || n == 1) {
    return BigInteger.ONE;
  }
  return fib(n - 2).add(fib(n - 1));
}

public static void main(String[] args) {
  for (int i = 0; i < 10; i++) {
    System.out.println(fib(i));
  }
}
Community
  • 1
  • 1
Wickramaranga
  • 943
  • 2
  • 19
  • 35