0
public class ModFib
{
    public static int modFibonacci(int term)
    {
        if(term == 1)
        {
            return 3;
        }
        else if(term == 2)
        {
            return 5;
        }
        else
        {
            return modFibonacci(term - 1) + modFibonacci(term - 2) + modFibonacci(term - 3);
        }
    }
}

it works fine at only term - 3 but this gives a stack overflow error.

4
  • "it works fine at only term - 3 but this gives a stack overflow error." can you rephrase that a bit clearer please Commented Mar 17, 2017 at 7:56
  • 1
    once you hit term = 3, you recursivly end up with modFibonacci(3-3), which will end in an endless recursion, as your break condition wont ever be met again, as term wont ever get to be 1 or 2 again and you´ll endlessly end up the in the else part recursivly calling your method. Commented Mar 17, 2017 at 7:56
  • @Bango Sorry for lack of clarity. return modFibonacci(term - 1) + modFibonacci(term - 2) works fine but when i add the third term it stops working. Commented Mar 17, 2017 at 7:57
  • @SomeJavaGuy Thank you very much. Commented Mar 17, 2017 at 7:59

1 Answer 1

2

need to add condition like

if(term == 0)
    {
        return 0;
    }
Sign up to request clarification or add additional context in comments.

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.