GATE / CS ARCHIVE

GATE CSE 2018 / QUESTION 45

Counting prints in recursive cycles

Programming in C · Recursion · Full GATE CSE 2018 paper

GATE 2018, Q45 2 marks · NAT
Report issue

Recursion

Question 45, GATE 2018: Count(x,y) does nothing if y==1. Otherwise, if x!=1 it prints * and calls Count(x/2,y); if x==1 it calls Count(1024,y−1). Integers use truncating division. How many prints result from Count(1024,1024)?
Tap to enlarge
Answer & solution

Official answer: 10230

Method

Separate the fast-changing variable x from the outer progress variable y. For each y>1, x halves ten times, since 1024=210. The x=1 call performs no print and starts the next y cycle with x reset. Values of y that produce prints are 1024 down through 2, a total of 1023, not 1024. The terminal y=1 call returns immediately, regardless of its x value. This counts executed print statements, not recursive invocations.

Solution

For a fixed y>1, x takes 1024, 512,..., 2, yielding 10 prints before reaching 1. Then y decreases by 1 and x resets to 1024. This occurs for y=1024, 1023,..., 2, namely 1023 rounds. At y=1 the function stops without printing. Therefore there are 10*1023=10230 prints in the abstract pseudocode model.

Original paper, page 19 · Answer key