dimanche 19 mars 2017

Recursive function to get sequence not working correctly

I am trying to program a sequence x(n) in C with the following conditions:

    x(0)=x
    x(n)=1 if x(n-1)=1
    x(n)=3*x(n-1)+1 if x(n-1)!=1 and x(n-1) not even
    x(n)=x(n-1)/2 if x(n-1) even

I tried the following:

  int sequence(int x, int n){

    if(n==0){
     return x;
    }


    if (sequence(x,n-1)==1){
     return 1;
    }

   if((sequence(x,n-1)!=1)&&((sequence(x,n-1)%2)!=0)){

      return 3*sequence(x,n-1)+1;

    }

    if((sequence(x,n-1)%2)==0){
     return sequence(x,n-1)/2;
    }


  }

It should give me the n-th element of the sequence with the starting point x. However, it does not work...

Aucun commentaire:

Enregistrer un commentaire