MarkS13
MarkS13

Reputation: 1

Recursive Collatz Function in C++

In order to count the number of times the Collatz conjecture must be implemented in order to get the result 1, I implemented a recursive counter function which uses two parameters, specifically the number and the counter.

unsigned int count_collatz_rec(int num, unsigned int count) {
    if(num == 1){
        count = count + 0;
    }
    else{
        count++;
        num = collatz(num);
        count = count_collatz_rec(num, count);
    }
    return count;
}

Is there any way to implement this function by using only one parameter, specifically 'num'?

Upvotes: 0

Views: 341

Answers (1)

StPiere
StPiere

Reputation: 4253

I think something like this could work:

  unsigned int count_collatz_rec(int num)
  {
        return (num <= 1) ? 1 : 1 + count_collatz_rec(collatz(num));
  }

Upvotes: 1

Related Questions