-1
#include <cs50.h>

int collatz(int n);

int main(void)
{
    int n = get_int("Enter int: ");
    int steps = collatz(n);
    printf("%i\n", steps);
}

int collatz(int n)
{
    if (n==1)
    {
        return 0;
    }

    else if ((n%2)==0)
    {
        return 1 + collatz(n/2);
    }

    else
    {
        return 1 + collatz(3 * n + 1);
    }
}

I am geting stuck trying to visualise how the 'return 1' on each iteration of the function gets 'carried through'.

I can write the steps out on paper to show that it does work, however I am struggling to make clear in my mind without going through step-by-step, why you have to +1 on every iteration of collatz.

Dan
  • 11
  • 3
  • There is no `return 1`. There is `return 1+ ` – Eugene Sh. Feb 10 '22 at 17:53
  • Try proving by induction that the function returns the number of steps. This way you don't need to visualise anything. – n. m. could be an AI Feb 10 '22 at 17:53
  • Try understanding a simpler recursion: `int foo(int n) { if (n == 0) return 1; else return 1+foo(n-1); }` – Eugene Sh. Feb 10 '22 at 18:00
  • You should write the code using tail recursion: `int collatz(int n, int s){return n<2 ? s : collatz(n&1 ? n*3+1 : n>>1, s+1);}` easier to understand, easier for a compiler to optimize. – EOF Feb 10 '22 at 18:03

2 Answers2

0

This code:

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

says: If there are no steps to perform (because n is already 1), return zero.

Otherwise, this code:

    else if ((n%2)==0)

selects one of the following:

        return 1 + collatz(n/2);

or:

        return 1 + collatz(3 * n + 1);

Each of those performs one step (either n/2 or 3 * n + 1) and then calls collatz to find out how many steps it takes to finish with that value. When collatz returns the number of steps needed for n/2 or 3 * n + 1, this code adds one for the step performed here. That gives the number of steps needed for n, which this code then returns.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

Try to visualize it as follows:

starting number: 3

** collatz(3): return 1 + collatz(10); **

collatz(10): return 1 + collatz(5);

** collatz(3): return 1 + (1 + collatz(5)); **

collatz(5): return 1 + collatz(16);

** collatz(3): return 1 + (1 + (1 + collatz(16))); **

collatz(16): return 1 + collatz(8);

** collatz(3): return 1 + (1 + (1 + (1 + collatz(8)))); **

collatz(8): return 1 + collatz(4);

** collatz(3): return 1 + (1 + (1 + (1 + (1 + collatz(4))))); **

collatz(4): return 1 + collatz(2);

** collatz(3): return 1 + (1 + (1 + (1 + (1 + (1 + collatz(2)))))); **

collatz(2): return 1 + collatz(1);

collatz(1): return 0;

** collatz(3): return 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0; **
machine_1
  • 4,266
  • 2
  • 21
  • 42