Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 256
Deneb A. Avatar asked Apr 18 '13 14:04

Deneb A.


1 Answers

How about this:

public static int chain(int n) {
    return chain(n, 0);
}

private static int chain(int n, int count) {
    if (n > 1) {  // no need for a while-loop, it will never get past 1 iteration
        if (n % 2 == 0) {
            return chain(n / 2, count + 1);
        }
        return chain(3 * n + 1, count + 1);
    }
    return count;
}

To me, this seems cleaner than declaring a static field outside of the method, primarily because I wouldn't want to worry about having to reset the static field to 0 every time I call chain.

like image 90
arshajii Avatar answered Sep 29 '22 12:09

arshajii