0

I'm writing an recursion method to calculate collatz conjecture for a sequence of positive integers. However, instead of stopping the calculation when the value reaches 1, I need it to stop when the value become smaller than or equal to the original value. I can't figure out what condition I should put in the if statement.

int collatz (int n) {
    printf("%d%s", n, " ");

    if(n > collatz(n)) {   // here I would get an error saying all path leads to the method itself 
        return n;
    }
    else {
        if(n % 2 == 0) {
            return collatz(n / 2);
        }
        else {
            return collatz((3 * n) + 1);
        }
    }
}
Aleksandar Stojadinovic
  • 4,851
  • 1
  • 34
  • 56
Ace_J
  • 87
  • 7

1 Answers1

1

I used two more parameters:

  1. startValue, to pass through the recursive calls the initial value and
  2. notFirstTime, to check if it is the first call (and not a recursive call). In this case a value n <= startValue is allowed.

Here the code:

int collatz (int startValue, int n, int notFirstTime){
    printf("%d%s ", n, " ");

    if(n <= startValue && !notFirstTime)
    {   // here I would get an error saying all path 
        //leads to the method itself
        return n;
    }
    else
    {
        if ( n%2==0 )
        {
            collatz(startValue, n/2, 0);
        }
        else 
        {
            collatz(startValue, (3*n)+1, 0);
        }
    }
}

int main() {
    int x = 27;
    int firstTime = 1;
    int test = collatz(x,x, firstTime);
    printf("\nLast value: %d\n", test);
    return 0;
}

Please note that I removed two return statements from the recursive calls.

acornagl
  • 521
  • 5
  • 24