0

I am trying to write a recursive algorithm to compute Fibonacci numbers. However, the program struggles with printing out the results.

My idea was to store each calculated value into an array (so the algorithm should be faster).

My desired output:

The fibonacci of n = 1 is fn= 1    
The fibonacci of n = 2 is fn= 2    
The fibonacci of n = 3 is fn= 2    
The fibonacci of n = 4 is fn= 3
...
The fibonacci of n = 8 is fn= 21
public class fibonacciCalculator {

    static int[] arr = new int[50];

    static int fibo (int n, int arr[]) {
        if ( n == 0 ) {
            return 0; 
        }else if ( n == 1 ) {
            return 1; 
        } 
        if ( arr[n-1] == 0) {
            arr[n-1] = fibo(n-1, arr);  
        }
        if ( arr[n-2] == 0) {
            arr[n-2] = fibo(n-2, arr);
        }
        return arr[n-1] + arr[n - 2];
    } 

    public static void main(String[] args) {

        for (int i = 1; i == 8; i++) {
            if (arr [i] == 0) {
                fibo(i, arr);
                int x = arr[i];
                String a = String.format("The fibonacci of n = %d is fn= %d", i , x);
                System.out.println(a);
                }
        }
    }
}
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 1
    One obvious problem is in your for loop `for (int i = 1; i == 8; i++)` which does nothing, since the repeat condition `i == 8` is already false in the first iteration. You probably meant `for (int i = 1; i <= 8; i++)`. – mrhd Nov 09 '19 at 15:31
  • Okay, that was the solution. it works now :) –  Nov 09 '19 at 15:53

3 Answers3

0

You can do this without declaring an array. This way, the intermediate values are stored in the execution stack:

public class fibonacciCalculator {

    static int fibo (int n) {
        if ( n == 0 ) {
            return 0; 
        } else if ( n == 1 ) {
            return 1; 
        } else {
            return fibo(n-2) + fibo(n-1);  
        }
    } 

    public static void main(String[] args) {

        for (int i = 1; i <= 8; i++) {
            int x = fibo(i);;
            String a = String.format("The fibonacci of n = %d is fn= %d", i , x);
            System.out.println(a);
        }
    }
}
mrhd
  • 1,036
  • 7
  • 16
  • That's true but on higher values, the code gets slow as he has to go recursive down for every number. my solution for this would be to store a calculated value and us it the next time again. –  Nov 09 '19 at 15:51
  • Oh, I see your point. For higher numbers, storing the intermediate results in a Dynamic Programming manner makes a lot of sense. – mrhd Nov 09 '19 at 16:02
0

Here is one way to do it.

   public int[] fib(int values[], int count) {
      if (count <= 0) {
         return values;
      }

      int k = values.length + 1;
      values = Arrays.copyOf(values, k);

      values[k - 1] = values[k - 2] + values[k - 3];
      return fib(values, count - 1);
   }

But an even better way is to memoize the values as you create them. This permits you to start calculating at the last computed terms and then continue until you meet your goal. If you specify a value less than the number computed, only those requested are returned.

A defensive copy of the list is used so you can't taint the returned sublist.

   List<Integer> fibs = new ArrayList(List.of(0, 1));
   public List<Integer> fib(int count) {
      int s = fibs.size();
      if (count < s) {
         // return a defensive copy to protect cached values.
         return new ArrayList<>(fibs.subList(0, count));
      }
      int e = fibs.get(s - 1) + fibs.get(s - 2);
      fibs.add(e);
      return fib(count);
   }
WJS
  • 36,363
  • 4
  • 24
  • 39
0

Okay to close this up I will post the working code. Maybe that will help anyone else.

public class fibonacciCalculator {
    static int[] arr = new int[48];
    static int fibo (int n, int arr[]) {
        if ( n == 1|| n == 2 ) {
            return 1; 
        }else if ( n == 0 ) {
            return 0; 
        }
        if (arr[n-1] == 0) {
            arr[n-1] = fibo(n-1, arr);
        }
        if (arr[n-2] == 0) {
            arr[n-2] = fibo(n-2, arr);
        }
        return arr[n-1] + arr[n - 2];
    }   
    public static void main(String[] args) {

        for (int i = 1; i <= arr.length-1; i++) {
            if (arr [i] == 0) {
                arr[i] = fibo(i, arr);
                System.out.print("The Fibonacci number " + i);
                System.out.println(" is: " + arr[i]);
            }       
        }
    }
}

However ... int will exceed its limit at Fibonacci 48. If you want higher values int should be replaced to long. but after that well don't know.. :D Greetings Synix