Iterative Version of Modified Fibonacci Sequence

旧城冷巷雨未停 提交于 2019-12-04 18:44:42

As a hint, notice that the above algorithm works by "cycling" the numbers through some variables. In the above code, at each point you are storing

 F_0    F_1
  a      b

You then "shift" them over by one step in the loop:

 F_1    F_2
  a      b

You then "shift" them again in the next loop iteration:

 F_2    F_3
  a      b

If you want to update the algorithm sum the last three values, think about storing them like this:

 T_0    T_1    T_2
  a      b      c

Then shift them again:

 T_1    T_2    T_3
  a      b      c

Then shift them again:

 T_2    T_3    T_4
  a      b      c

Converting this intuition into code is a good exercise, so I'll leave those details to you.

That said - there is a much, much faster way to compute the nth term of the Fibonacci and "Tribonacci" sequences. This article describes a very clever trick using matrix multiplication to compute terms more quickly than the above loop, and there is code available here that implements this algorithm.

Hope this helps!

I like recursion. Call me a sadist.

static int rTribonacci (int n, int a, int b, int c) {
    if (n == 0) return a;
    return rTribonacci (n-1, b, c, a + b + c);
}

int Tribonacci (int n) { return rTribonacci(n, 0, 0, 1); }

I don't normally answer questions that "smell" like homework, but since someone else already replied this is what I would do:

int Tribonacci(int n)
{
    int last[3] = { 0, 0, 1 }; // the start of our sequence

    for(int i = 3; i <= n; i++)
        last[i % 3] = last[i % 3] + last[(i + 1) % 3] + last[(i + 2) % 3];

    return last[n % 3];
}

It can be improved a bit to avoid all the ugly modular arithmetic (which I left in to make the circular nature of the last[] array clear) by changing the loop to this:

    for(int i = 3; i <= n; i++)
        last[i % 3] = last[0] + last[1] + last[2];

It can be optimized a bit more and frankly, there are much better ways to calculate such sequences, as templatetypedef said.

If you want to use recursion, you don't need any other parameters:

int FibonacciN(int position)
{   if(position<0) throw new ArgumentException("invalid position");
    if(position==0 || position ==1) return position;
    return FibonacciN(position-1) + FibonacciN(position-2);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!