Recursive Iteration looping forever after first

I have very simple code, that for a SOSA STRADONITZ number returns the generation of the person:

1 is 1

2-3 is 2

4-7 is 3

8-15 is 4

16-13 is 5

(…)

The code is the follwing, but it does not return ever after the second point, why?

public static void main(String[] args) {
        FamilyTree f = new FamilyTree(null);
        for (int i = 1; i <= 2; i++) {
            f.getGeneration(i);
            System.out.println("returned!");
        }
    }

public int getGeneration(int sosa) {
        System.out.println("SOSA: " + sosa);
        int toRet = 1;
        while ((int) sosa / 2 != 0) {
            toRet++;
            getGeneration((int) sosa / 2);
        }
        return toRet;
    }

it prints:

SOSA: 1

returned!

SOSA: 2

SOSA: 1

SOSA: 1

SOSA: 1

(SOSA: 1) forever

>Solution :

Once the while loop is entered, there is no way to terminate, as you never change sosa. Dividing it by 2 each time in the loop will fix this.

A few other notes:

  • You can initialize toRet to 0 and check for sosa being non-zero rather than sosa / 2 being non-zero.
  • There is no need to cast sosa / 2 to int as the result of the division of two ints is guaranteed to be an int.
public int getGeneration(int sosa) {
    int toRet = 0;
    while (sosa != 0) {
        toRet++;
        sosa /= 2;
    }
    return toRet;
}

This can also be simplified by looking at the binary representation of the input:

return 32 - Integer.numberOfLeadingZeros(sosa);

Leave a Reply