ProgrammingHardCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
int calls = 0;
unsigned g(unsigned a, unsigned b) {
    calls++;
    return b == 0 ? a : g(b, a % b);
}
int main(void) {
    unsigned r = g(1071, 462);
    printf("%u %d", r, calls);
}
  1. A. 21 3
  2. B. 7 4
  3. C. 21 5
  4. D. 21 4

Correct answer: D. 21 4

Euclid's algorithm gives gcd 21, and the recursion makes four calls: (1071, 462), (462, 147), (147, 21) and (21, 0). Counting only the recursive steps gives 3.

More C Programming questions

Exams that ask this topic