Recursion

AP Computer Science A· difficulty 4/5

public static int pow(int b, int e) {
    if (e == 0) return 1;
    if (e % 2 == 0) {
        int half = pow(b, e / 2);
        return half * half;
    }
    return b * pow(b, e - 1);
}
// Call: System.out.println(pow(2, 5));

What is printed?

  • A

    10

  • B

    32

    check_circle
  • C

    8

  • D

    16

Explanation

pow(2,5) = 2*pow(2,4). pow(2,4) = pow(2,2)*pow(2,2). pow(2,2)=pow(2,1)<em>pow(2,1)... result 16. So 2</em>16 = 32.

Want 10 more like this — adaptive to your weak spots?

Related questions