Recursion

AP Computer Science A· difficulty 5/5

public static int g(int n) {
    if (n <= 0) return 0;
    return n + g(n - 2);
}
public static int h(int n) {
    if (n <= 0) return 1;
    return g(n) * h(n - 1);
}
// Call: System.out.println(h(3));

What is printed?

  • A

    36

  • B

    12

  • C

    8

    check_circle
  • D

    48

Explanation

g(1)=1, g(2)=2+g(0)=2, g(3)=3+g(1)=4. h(0)=1, h(1)=g(1)*h(0)=1, h(2)=g(2)*h(1)=2, h(3)=g(3)<em>h(2)=4</em>2=8.

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

Related questions