Find the n members of the sequence X(1)=X(2)=X(3)=1; X(n)=X(n-1)+X(n-3) X(1)=X(2)=X(3)=1; X(n)=X(n-1)+X(n-3) , i.e. enter n from the keyboard and need to display:

1 1 1 2 3 4 6 9 13 19 28 41, etc. to n

Is it possible to complete this task without using an array?

  • I think they missed a deuce: 1 1 1 2 3 4 6 ... - andrybak
  • A linked lists are not considered? - 3JIoi_Hy6

3 answers 3

You can use recursion, here it is most obvious. Or a cycle of this type:

 int a=1; int b=1; int c=1; int d=2; int t; for (int i = 1; i<=n; i++) { if (i < 4) { printf(i); } else { t=a+c; printf(t); b = c; c = t; a = b; } printf(" "); } 

It will be a little more efficient.

    Can. You just need to store only the last 4 calculated elements of the sequence.

      Maybe. After all, to calculate each of the following elements, you need to know only three previous ones:

       int xnm1 = 1, xnm2 = 1, xnm3 = 1; cout << "1 1 1 "; int n; cin >> c; for (int i = 4; i <= n; ++i) { int xn = xnm1 + xnm3; xnm3 = xnm2; xnm2 = xnm1; xnm1 = xn; cout << xn << " "; } 
      • It seems to me, or declaring a variable in a loop is a bad idea? ;) - uramer239 5:46 pm
      • Why? It is a normal move. Anyway, non-optimizing compilers, so it is possible that this "variable" will never leave the limits of processor registers. - gecube