ProgrammingVery hardCompetitive coding (CP)
How many times is disk 3 moved in this recursive Towers of Hanoi with 5 disks? Compute the program output.
How many times is disk 3 moved in this recursive Towers of Hanoi with 5 disks? Compute the program output.
#include <stdio.h>
int cnt = 0;
void h(int n, char f, char t, char v) {
if (n == 0) return;
h(n - 1, f, v, t);
if (n == 3) cnt++;
h(n - 1, v, t, f);
}
int main(void) {
h(5, 'A', 'C', 'B');
printf("%d", cnt);
}- A. 2
- B. 8
- C. 4
- D. 6
Correct answer: C. 4
Disk k moves 2^(n-k) times in an n-disk puzzle, so disk 3 in a 5-disk puzzle moves 2^2 = 4 times. The recursion reaches the n == 3 step exactly once for each such move.
More C Programming questions
- How many integers n with 1 <= n <= 64 satisfy both (n & (n - 1)) == 0 and (n & 0x55555555u) != 0? Compute with this program. c #include…
- What is printed? c #include <stdio.h> int main(void) { int a[5]; int p = a + 4, q = a + 1; printf("%ld", (long)(p - q) (long)sizeof p); }
- What is printed? Assume int is 32 bits and integer division truncates toward zero. c #include <stdio.h> int main(void) { int v[] = {-7…
- What is the maximum value of depth printed? c #include <stdio.h> int depth = 0, maxd = 0; void r(int n) { depth++; if (depth > maxd) maxd…
- What is printed? c #include <stdio.h> int main(void) { int a[] = {1, 2, 3, 4, 5}; int p = a + 2; printf("%d %d", p[-1], p[2]); }
- What is printed? Assume uint32t is 32 bits. c #include <stdint.h> #include <stdio.h> uint32t rotl(uint32t x, unsigned k) { return (x << k)…