Search code examples
cfunctionif-statementrecursionansi-c

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...


Solution

  • Your code does what you proposed it to do. Maybe your original logic is flawed.

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

    You can clean up your code somewhat to improve its readability and make it slightly faster/better.

    int sequence(int x, int n){
      if(n==0){
        return x;
      }
    
      if (sequence(x,n-1)==1){
        return 1;
      }
    
      if((sequence(x,n-1)%2)!=0){
        return 3*sequence(x,n-1)+1;
      }
    
      return sequence(x,n-1)/2;
    }