Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading