retagged by
733 views
1 votes
1 votes
Consider the following program :
double DO (double X , long int n )
{
double A;
if ( n = = 1 )
return X ;
A = DO (X , n / 2);
if ( n % 2 )
return X * A * A;
return A * A;
}

 

 

 

 

What does DO do ?
(A)X n
(B)n X
(C)X n+1
What number of multiplications are taking place if X = 2 and n = 37
(A)37
(B)36
(C)7
(D)6

ans wid solutn plz
retagged by

1 Answer

2 votes
2 votes

The function DO computes pow(x, n), ie, x raised to n.

For X = 2, N = 37 there would be following sequence of calls:

DO (2, 37)

    DO (2, 18)

        DO (2, 9)

            DO(2, 4)

                DO(2, 2)

                    DO(2, 1)  // end of recursion

DO(2, 1) will not have any multiplications.

For odd N there would be 2 multiplications and for even N there would be 1 multiplication.

Number of odd N's == 2 (9, 37 -> Note we exclude 1)

Number of even N's == 3 (2, 4, 18)

Therefore number of multiplications should  be 2*2 + 3*1 == 4 + 3 == 7.

Please verify if that answer is correct, I did not verify it.

Related questions

0 votes
0 votes
2 answers
1
Debargha Mitra Roy asked Apr 10
120 views
What is the output of the below code?#include <stdio.h void main() { static int var = 5; printf("%d ", var ); if (var) main(); }a. 1 2 3 4 5b. 1c. 5 4 3 2 1d. Error
3 votes
3 votes
3 answers
2
Laxman Ghanchi asked May 19, 2023
1,177 views
#include<stdio.h void print(int n) { printf("Hello "); if(n++ == 0) return ; print(n); n++; } int main() { void print(); print(-4); }How many times printf execute?? And H...
0 votes
0 votes
1 answer
3
Laxman Ghanchi asked May 19, 2023
693 views
#include<stdio.h>void print(int n){ printf("Hello "); if(n++ == 0) return ; print(n); n++;}int main(){ void print(); print(-4);}