Recursion

AP Computer Science A· difficulty 5/5

public static int t(int n) {
    if (n < 3) return n;
    return t(n-1) + t(n-2) + t(n-3);
}
// Call: System.out.println(t(5));

What is printed?

  • A

    7

  • B

    11

    check_circle
  • C

    5

  • D

    13

Explanation

Base: t(0)=0, t(1)=1, t(2)=2. t(3)=t(2)+t(1)+t(0)=3. t(4)=t(3)+t(2)+t(1)=6. t(5)=t(4)+t(3)+t(2)=6+3+2=11.

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

Related questions