The question is the sequence starts with three ones and then every number after that is the sum of the three numbers that precede it. For example:
3 = 1 + 1 + 1
5 = 3 + 1 + 1
9 = 5 + 3 + 1
17 = 9 + 5 + 3
31 = 17 + 9 + 5
Write a function that takes a single integer parameter named n. This function should then calculate and return the n-th integer in the sequence defined above. So, for example:
println(theSequence(1)); // Would output 1
println(theSequence(2)); // Would output 1
println(theSequence(3)); // Would output 1
println(theSequence(4)); // Would output 3
println(theSequence(5)); // Would output 5
println(theSequence(6)); // Would output 9
println(theSequence(7)); // Would output 17
// skipping ahead a few...
println(theSequence(37)); // Would output 1467182629
Alright, so what have you gotten done so far?
Have you defined the function correctly?
Does it take the proper parameter?
Does it work out the desired value?
No one is going to do your assignment for you! Please put some effort in - and show us the products of that effort!
hmm… @TfGuy44 so true.
but i will give you a clue
you can solve this recursively.
take the formula. it just sum 3 sequences preceed it. so
sequence(i) = sequence(i-1) + sequence(i - 2) + sequence(i-3)
as simple as that!
I don’t know if your tutor expects you to use recursion but this problem is not suitable unless you store intermediate values in a data structure such as an array.
The time taken to perform a true recursive solution to this problem would increase exponentially as the sequence term number increases.
I suggest an iterative solution where you simply loop through the elements calculating each one in turn. At any time you only need to remember the last 3 terms.