ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int calls = 0;
int ways(int n) {
    calls++;
    if (n < 0) return 0;
    if (n == 0) return 1;
    return ways(n - 1) + ways(n - 3) + ways(n - 4);
}
int main(void) {
    int r = ways(6);
    printf("%d %d", r, calls);
}
  1. A. 8 46
  2. B. 9 46
  3. C. 9 28
  4. D. 9 40

Correct answer: B. 9 46

ways(n) counts ordered sums of 1, 3 and 4 equal to n. Bottom up: w(0)=1, w(1)=1, w(2)=1, w(3)=2, w(4)=4, w(5)=6, w(6)=9 (w(5)+w(3)+w(2) = 6+2+1). Calls also count the negative-argument calls: C(n) = 1 for n ≤ 0, else 1 + C(n−1) + C(n−3) + C(n−4); C(1)=4, C(2)=7, C(3)=10, C(4)=16, C(5)=28, C(6)=46.

More C Programming questions

Exams that ask this topic