Any idea on how can I count the number of elements that verify an "if" condition?

java

Solution

Remove the `count` variable from your method, and make it a static member of your class. And to prevent repeating yourlsef (DRY principle), you should increment the `count` variable at the top of your method.

private static int count = 0;

private static int chain(int n) {
    count++;

    while(n > 1) {
        if(n % 2 == 0) {
            return chain(n/2);
        }

        return chain(3*n+1);
    }

return count;
}

Problem

``` private static int chain(int n){ int count = 0; while(n > 1){ if(n % 2 == 0){ count++; //the value is not stored return chain(n/2); } count++; //same thing return chain(3*n+1); } return count; //prints the initial value (0) } } ``` I need to print the number of times the chain method reoccurs.

Original source