Hey everyone I am trying to write a recursive function for a perrin sequence where it returns the nth term that a user enters which is:
<code>P(0) = 3, P(1) = 0, P(2) = 2,
</code>
<code>P(0) = 3, P(1) = 0, P(2) = 2,
</code>
P(0) = 3, P(1) = 0, P(2) = 2,
and
<code>P(n) = P(n − 2) + P(n − 3) for n > 2.
</code>
<code>P(n) = P(n − 2) + P(n − 3) for n > 2.
</code>
P(n) = P(n − 2) + P(n − 3) for n > 2.
The sequence of Perrin numbers starts with
<code>3, 0, 2, 3, 2, 5, 5, 7, 10, 12, 17, 22, 29, 39 ...
</code>
<code>3, 0, 2, 3, 2, 5, 5, 7, 10, 12, 17, 22, 29, 39 ...
</code>
3, 0, 2, 3, 2, 5, 5, 7, 10, 12, 17, 22, 29, 39 ...
I know I should put some sort of code in here but I am totally lost. We just learned recursive functions this week and I cannot figure out how to do this.
1
This could be a good way to start with TDD.
- First write method p in that way it returns 3 if argument is equal to 0
- You assert that via checking if p(0) == 3
- run the program
- Then you modify method p that it returns 0 if argument is equal to 1
- You assert that via checking if p(1) == 0
- run the program (you might guessed it)
- Then you modify method p that it returns 2 if argument is equal to 2
- You assert that via checking if p(2) == 2
- run the program (you might guessed it already)
Small hint: all checks/test must be okay – not in a series, but all together.
Yeah you did it the first part for the first three numbers.
- then you modify the method to enter a special branch if n is larger than 2
- Now comes the interesting part what to return here?
- write a test which asserts that p(3) == 3
- try something to make it return the value 3
- maybe plainly return p(0)
- run the program (you might guessed it already too)
- write a test which asserts that p(4) == 2
- you fail, now try something else
- return the sum of p(n-2) and p(n-3)
- run the program (did that?)
- assert more values….
- run the program (you should know that now.)
1