The Gateway to Computer Science Excellence
0 votes
99 views

Consider the following C code. Assume that unsigned long int type length is 64 bits.

unsigned long int fun(unsigned long int n) {

        unsigned long int i, j, sum = 0;

        for( i = n; i > 1; i = i/2) j++;

        for( ; j > 1; j = j/2) sum++;

        return sum;

}

The value returned when we call fun with the input 240 is

 

4

 

5

C

6

D

40
closed as a duplicate of: GATE2018-32
in Programming by (129 points)
closed by | 99 views
0
Gate Questions are already answered...

1 Answer

0 votes
ans would be 5.
explaination - 1st notice - the two for loops are separate that is 2nd loop in not inner loop of 1st loop.
now in the 1st loop--
  j = 0 | i = 2^40
  j = 1 | i = 2^39
  j = 2 | i = 2^38
.... and so on until
  j = 39 | i = 2^1

  j = 40 | i = 2^0
at the end  of 1st for loop j = 40, so mathematically the for loop is finding  floor of (log2(n))

now in 2nd for loop, similarly it is finding floor of (log2(j)) that is floor( log2(40))  =  5
by Junior (925 points)

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,385 answers
198,557 comments
105,368 users