-4

the result of the code below is : 3877337276612781506 but i tried online Fibonacci calculator and got huge number of more than 1000 decimals

in such numbers how can i got the Fibonacci result?

Long fnOfZero = 0L, fnOfOne = 1L, n, i, count = 8182L;
for (i = 2L; i < count; ++i){
  n = fnOfZero + fnOfOne;
  System.out.print(i + ":  ");
  System.out.println(n));
  fnOfZero = fnOfOne;
  fnOfOne = n;
}
bugs
  • 14,631
  • 5
  • 48
  • 52
Hany Omar
  • 3
  • 4
  • 4
    What do you mean "the Fibonacci of numbers like 8181"? Fibonacci numbers are a sequence, not a function. – khelwood Apr 18 '18 at 08:36
  • fibonacci of big numbers like 8181 – Hany Omar Apr 18 '18 at 08:37
  • You didn't go look at how many bytes can be stored in a long. It sits at 8 bytes with a range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Your number cannot go higher because it's limited by the datatype – L_Church Apr 18 '18 at 08:41
  • this is the function of fibonacci: `f{n}=f_{{n-1}} + f_{{n-2}}` – Paplusc Apr 18 '18 at 08:42
  • 2
    If you use a biginteger instead of a long you will be able to store 100 digits whereas a long can only store 19 – L_Church Apr 18 '18 at 08:44
  • 1
    If you want a `double` estimation: `Math.pow((1 + Math.sqrt(5))/2, n) / Math.sqrt(5)`; if value is too big for `double` you can work with *logarithms*. – Dmitry Bychenko Apr 18 '18 at 08:47
  • even BigInteger can not store the result !! – Hany Omar Apr 18 '18 at 08:55
  • Possible duplicate of [Large Numbers in Java](https://stackoverflow.com/questions/849813/large-numbers-in-java) – Ole V.V. Apr 18 '18 at 09:11

2 Answers2

1
    BigInteger secondLast = BigInteger.ZERO;
    BigInteger last = BigInteger.ONE;
    int count = 8182;
    for (int i = 2; i < count; ++i) {
        BigInteger n = secondLast.add(last);
        secondLast = last;
        last = n;
    }
    System.out.println(last);

It prints a number with 1710 digits in it.

I used your algorithm and just substituted BigInteger for Long as already said in the comment.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
-1

You may give Big Decimal a try.

Raj Roy
  • 1
  • 1