Unfold the loop three times

153 views Asked by At

I got this Java function and I have to write the piece of code which results by unfolding the loop three times. What does it mean?

int f(int x, int y) {
   while (true) {
       int m = x % y;
       if(m == 0) return y;
       x = y;
       y = m;
   }
}
1

There are 1 answers

0
Andreas On

It means to repeat the code inside the loop a number of times, then refactoring the code to optimize it.

Let's see how it goes if we repeat once.

int f(int x, int y) {
    while (true) {
        int m = x % y;
        if(m == 0) return y;
        x = y;
        y = m;
        
        m = x % y;
        if(m == 0) return y;
        x = y;
        y = m;
    }
}

By rotating the use of the variables, we can eliminate the two simple assignments in the middle, thereby optimizing the code.

int f(int x, int y) {
    while (true) {
        int m = x % y;
        if(m == 0) return y;
        
        x = y % m;
        if(x == 0) return m;
        y = x;
        x = m;
    }
}

Now repeat it one more time, and rotate the variables in the third copy, for a total of 3 times the "same" code, as specified in the assignment.

I'll leave it to you to do that, since it is your assignment to complete. If done correctly, you'll find that there are no simple assignments in the result.