Skip to content
Official PYQ · 1991

GATE CS 1991 Q03-viii — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Consider the following Pascal function:

Function X(M:integer):integer;
Var i:integer;
Begin
    i := 0;
    while i*i < M
    do i:= i+1
    X := i
 end

The function call X(N)X(N), if NN is positive, will return

Choose one option
View worked solution

Answer: C

To find what the function returns for a positive integer NN, let us analyze the loop condition and termination behavior.

The loop starts with i=0i = 0 and increments ii by 11 in each iteration as long as:

i2<Ni^2 < N

The loop terminates as soon as this condition becomes false, which means it stops at the smallest non-negative integer ii such that:

i2≥Ni^2 \ge N

Taking the square root on both sides (since i≥0i \ge 0 and N>0N > 0):

i≥Ni \ge \sqrt{N}

The smallest integer ii that is greater than or equal to N\sqrt{N} is, by definition, the ceiling of N\sqrt{N}:

i=⌈N⌉i = \lceil \sqrt{N} \rceil

Dry Run Examples:

  • Case 1: N=9N = 9 (a perfect square)
    • i=0  ⟹  02<9i = 0 \implies 0^2 < 9 (True)   ⟹  i=1\implies i = 1
    • i=1  ⟹  12<9i = 1 \implies 1^2 < 9 (True)   ⟹  i=2\implies i = 2
    • i=2  ⟹  22<9i = 2 \implies 2^2 < 9 (True)   ⟹  i=3\implies i = 3
    • i=3  ⟹  32<9i = 3 \implies 3^2 < 9 (False)   ⟹  \implies Loop terminates.
    • Returns 33, which is ⌈9⌉=3\lceil \sqrt{9} \rceil = 3.
  • Case 2: N=8N = 8 (not a perfect square)
    • i=0  ⟹  02<8i = 0 \implies 0^2 < 8 (True)   ⟹  i=1\implies i = 1
    • i=1  ⟹  12<8i = 1 \implies 1^2 < 8 (True)   ⟹  i=2\implies i = 2
    • i=2  ⟹  22<8i = 2 \implies 2^2 < 8 (True)   ⟹  i=3\implies i = 3
    • i=3  ⟹  32<8i = 3 \implies 3^2 < 8 (False)   ⟹  \implies Loop terminates.
    • Returns 33, which is ⌈8⌉=⌈2.828⌉=3\lceil \sqrt{8} \rceil = \lceil 2.828 \rceil = 3.

Thus, the function returns ⌈N⌉\lceil \sqrt{N} \rceil.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions