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

How does the f function end up with a value of 1024?

I’m trying to solve a sample test question and I’m having trouble understanding the last part of the problem. For the first print statement, I get 32. Using that same process I get a completely different value than the one returned by my compiler. The compiler returns 32 then 1024. Using the same logic I used to get 32, I’m confused on how the compiler gets 1024. Could anyone clearly explain what I’m doing wrong?

public static void main(String[] args) {
    System.out.println(f(2, 5));
    System.out.println(f(2, 10));
}
public static long f(long x, long y) {
    if (y == 0) {
        return 1;
    } 
    else if (y == 1) {
        return x;
    } 
    else {
        long z = y / 2;
        long e = f(x, z);
        if (y % 2 == 0) {
            return e * e;
        } 
        else {
            return x * e * e;
        }
    }
}

>Solution :

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

Just.. walk through it.

f(2, 10)

y is neither 0 nor 1, but is divisible by 2 so the else clause triggers, and the y%2 == 0 clause. e*e is returned, where e is f(2, 5).

f(2, 5)

y is neither 0 nor 1, and is not divisible by 2 so both else clauses trigger. x*e*e is returned, where x is 2 and e is f(2, 2).

f(2, 2)

y is neither 0 nor 1, but is divisible by 2 so the else clause triggers, and the y%2 == 0 clause. e*e is returned, where e is f(2, 1).

f(2, 1)

y is 1, therefore x is returned, which is 2.

Now go backwards

  • f(2, 1) = 2
  • f(2, 2) = e*e = 4
  • f(2, 5) = 2*e*e = 32
  • f(2, 10) = e*e = 1024
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