c - Working on a Fibonnaci/mysequence code -
i working on code suppose calculate sequence:
a(n+2)=-2(n+1)+3a(n) a(0)=2 a(1)= -1
unfortunately cannot figure out. i'm new @ (about month) , i'm going try best on own, need help. thank whoever decides me.
#include <stdio.h> int mysequence(int n) { if (n==0) return 2; if (n==1) return -1; if (n==2) return 8; return (2 * mysequence(n+1) + mysequence(n+2))/3; } int main() { int n; printf("enter n = "); scanf("%d", &n); printf("%d\n",mysequence(n)); return 0; }
look @ line return (2 * mysequence(n+1) + mysequence(n+2))/3
, compare know sequence: a(n+2)=-2(n+1)+3a(n)
.
they have nothing in common.
what want return (-2*mysequence(n-1) + 3*mysequence(n-2))
. why, coefficients should clear enough, copied definition. reason call next level of recursion n-1
, n-2
quite simple, observe:
a(n+2)=-2(n+1)+3a(n)
-> substitute n
n-2
-> a(n)=-2(n-1)+3a(n-2)
.
Comments
Post a Comment