0

Hello all beginner programmer here, having a hard time calculating a fibonacci series without recursion.

My main issue is using BigInteger with it. Here is my code :

import java.math.BigInteger;
public class Fibonacci
{
   public void fibonacci(int n)
   {
      int[] arr = new int[n + 1];

      arr[0] = 0;
      arr[1] = 1;
      arr[2] = 1;

      for(int i = 3; i <= n; i++)
      {
         arr[i] = arr[i-1] + arr[i-2];             
      }

      System.out.println(arr[n]);           
   }     
}

Here is my man method tester

public class TestFibonacci
{
   public static void main(String[] args)
   {
      Fibonacci f1 = new Fibonacci();

      f1.fibonacci(3);
      f1.fibonacci(10);
      f1.fibonacci(20);
      f1.fibonacci(30);
      f1.fibonacci(40);
      f1.fibonacci(50);
      f1.fibonacci(60);
      f1.fibonacci(100);
   }
}

My current output works up to 40 after I start getting the negative numbers, any tips??

2
55
6765
832040
102334155
-298632863
1820529360
-980107325
azro
  • 53,056
  • 7
  • 34
  • 70
Cmh4251
  • 3
  • 1

2 Answers2

0

Sure you'd better use BigInteger, because without you'll get integer overflow(link) :

public void fibonacci(int n) {
    BigInteger[] arr = new BigInteger[n + 1];

    arr[0] = BigInteger.ZERO;
    arr[1] = BigInteger.ONE;
    arr[2] = BigInteger.ONE;

    for (int i = 3; i <= n; i++) {
        arr[i] = arr[i - 1].add(arr[i - 2]);
    }

    System.out.println(arr[n]);
}

And you'll get :

2
55
6765
832040
102334155
12586269025
1548008755920
354224848179261915075
azro
  • 53,056
  • 7
  • 34
  • 70
  • Thanks Azro, still learning more and more about java and you have clarified exactly what I was asking. Also was it necessary for me to have to declare the first three big ints in the array? I figured I would have too. – Cmh4251 Jan 28 '18 at 22:26
-1

Just declare your array to store BigIntegers:

BigInteger[] arr = new BigInteger[n + 1];

Initialize your first values with the BigInteger.ONE and BigInteger.ZERO:

arr[0] = BigInteger.ZERO;
arr[1] = BigInteger.ONE;

At the end just use the add method:

arr[i] = arr[i - 1].add(arr[i - 1]);
thnkndblv
  • 40
  • 5