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);
}- A. 8 46
- B. 9 46
- C. 9 28
- 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
- What is printed? c int moves = 0; void h(int n, char from, char via, char to) { if (n == 0) return; h(n - 1, from, to, via); if (++moves…
- What is printed? c for (unsigned n = 5; n < 8; n++) printf("%u ", n ^ (n >> 1)); unsigned g = 13, b = 0; for (; g; g >>= 1) b ^= g…
- What is printed? c int walk(int n) { static int calls = 0; calls++; if (n > 1) { walk(n / 2); walk(n / 3); } return calls; } int…
- What is printed? c int calls = 0; int A(int m, int n) { calls++; if (m == 0) return n + 1; if (n == 0) return A(m - 1, 1); return A(m - 1…
- What is printed? c int a[7] = {1, 2, 3, 4, 5, 6, 7}, n = 7, i = 0; while (n > 1) { i = (i + 2) % n; printf("%d ", a[i]); for (int j = i; j…
- What is printed? c / LP64: 4-byte int, 8-byte pointers / void f(int m[][4], int n) { printf("%zu %zu %td ", sizeof m, sizeof m[0], (char…