2

I have the follow code for a recursive Fibonacci Sequence

    if (term < 2){
        System.out.print("1 ");
        return 1;
    } 
        int results = fibonacci(term - 1) + fibonacci(term - 2);
        System.out.print(results + " ");

        return results;

The output I get is

What term would you like to do the Fibonacci Sequence up to: 4

1 1 2 1 3 1 1 2 5 The 4th is 5

How do I make it so it prints

1 1 2 3 The 4th is 5

0

3 Answers 3

1

Use tail recursion.

  public static void main(String[] args) {

    System.out.print("The 10th is: " + fibonnaci(10));
  }

  public static int fibonnaci(int number) {
     return fibonnaciHelper(number, 1, 1);
  }

  public static int fibonnaciHelper(int term, int lower, int higher) {
      if (term < 2){
          return higher;

      } 

      System.out.print(higher + " ");
      int results = fibonnaciHelper(term - 1, higher, higher + lower);
      return results;
  }
Sign up to request clarification or add additional context in comments.

4 Comments

I understand how your program work, however, I would I get the print out of 1 1 2 3 5 8 13 ... with the recursion program that I wrote.
@Shi_No_Tenshi try System.out.println(fibnnoaci(6));
@Shi_No_Tenshi I don't understand your question
@Shi_No_Tenshi You can't. It's impossible.
0

Iterative fibionacci sequence - had it lying about somewhere

public static int fib(int n) {
            int prev1=0, prev2=1;
            for(int i=0; i<n; i++) {
                int savePrev1 = prev1;
                prev1 = prev2;
                prev2 = savePrev1 + prev2;
            }
            return prev1;
}

Comments

0

You could try something like the following:

public void fib(int n){
    if(n==0)
        System.out.println(1);

    else System.out.println(fib(1,n,0,1);
}

private int fib(int iteration, int limit, int n0, int n1){
    if(iteration==limit)
         return(n0+n1);

    fib(++iteration,limit,n1,(n0+n1));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.