ProgrammingHardProduct company OA · GATE CS

What is printed?

What is printed?
int m = 0;
long p(long b, int e) {
    if (e == 0) return 1;
    long h = p(b, e / 2);
    m++;
    if (e % 2) { m++; return h * h * b; }
    return h * h;
}
int main(void) {
    long r = p(3, 13);
    printf("%ld %d", r, m);
}
  1. A. 1594323 7
  2. B. 1594323 4
  3. C. 1594323 13
  4. D. 1594323 5

Correct answer: A. 1594323 7

e goes 13 → 6 → 3 → 1 → 0. m counts multiplications: two at each odd level (13, 3, 1) and one at the even level 6, so 2 + 1 + 2 + 2 = 7, far fewer than the 12 of the naive loop. 3^13 = 1594323. '4' counts calls, not multiplications.

More C Programming questions

Exams that ask this topic