ProgrammingVery hardCompetitive coding (CP)
How many ordered ways are there to write 10 as a sum of 1s and 4s? Compute with this program.
How many ordered ways are there to write 10 as a sum of 1s and 4s? Compute with this program.
#include <stdio.h>
int f(int n) {
if (n == 0) return 1;
if (n < 0) return 0;
return f(n - 1) + f(n - 4);
}
int main(void) {
printf("%d", f(10));
}- A. 12
- B. 14
- C. 11
- D. 16
Correct answer: B. 14
The recursion splits by the last part, which is 1 or 4, so f(n) = f(n - 1) + f(n - 4). The values for n = 0 to 10 are 1, 1, 1, 1, 2, 3, 4, 5, 7, 10, 14.
More C Programming questions
- What is printed? c #include <stdio.h> int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } int main(void) { printf("%d"…
- What is printed? c #include <stdio.h> int rev(int n, int acc) { return n == 0 ? acc : rev(n / 10, acc 10 + n % 10); } int main(void) {…
- What is printed? The program checks whether the low four bits of each argument form a binary palindrome. c #include <stdio.h> unsigned…
- What is printed? Assume unsigned int is 32 bits. c #include <stdio.h> int main(void) { unsigned x = 1, r = 0; for (int i = 0; i < 32; i++)…
- What is printed? c #include <stdio.h> int main(void) { unsigned n = 1000; int p = -1; while (n) { n >>= 1; p++; } printf("%d", p); }
- Would the product of 50000 and 50000 overflow a 32-bit int? The program checks with a 64-bit product. What is printed? c #include…