# Data Structure Questions and Answers-Power of a Number using Recursion in Logn Time

## Data Structure Questions and Answers-Power of a Number using Recursion in Logn Time

 Question 6 [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER]
What will be the time complexity of the following code?

`#include<stdio.h>  int power(int x,  int y) { int temp; if( y == 0) return 1; temp = power(x,  y/2); if (y%2 == 0) return temp*temp; else return x*temp*temp; } int main() { 	int x = 2; int y = 3; 	printf("%d",  power(x,  y)); 	return 0; }`
 A O(1) B O(n) C O(log n) D O(n log n)
Question 6 Explanation:
The given code is the optimized version for finding the power of a number. It forms a recurrence relation given by T(n)=T(n/2)+c which can be solved using master theorem. It is calculated to be equal to O(log n).

 Question 7 [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER]
What is the advantage of iterative code for finding power of number over recursive code?
 A Iterative code requires less time B Iterative code requires less space C Iterative code is more compiler friendly D It has no advantage
Question 7 Explanation:
Both iterative and recursive approach can be implemented in log n time but the recursive code requires memory in call stack which makes it less preferable.

 Question 8 [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER]
Which of the following correctly implements iterative code for finding power of a number?
 A `#include int power(int x, int y) { int res = 1; while (y > 0) { if (y & 1) res = res *` B `#include int power(int x, int y) { int res = 1; while (y > 0) { if (y && 1` C `#include int power(int x, int y) { int res = 1; while (y > 0) { if (y && 1) res = x *` D `#include int power(int x, int y) { int res = 1; while (y > 0) { if (y & 1) res = x *`
Question 8 Explanation:
It represents the iterative version of required code. It has a time and space complexity of O(log n) and O(1) respectively.

 Question 9 [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER]
Recursive approach to find power of a number is preferred over iterative approach.
 A True B False
Question 9 Explanation:
The recursive code requires memory in call stack which makes it less preferable as compared to iterative approach.

 Question 10 [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER]
What will be the output for following code?

`float power(float x,  int y) { 	float temp; 	if( y==0) 	return 1; 	temp = power(x,  y/2);	 	if (y%2 == 0) 		return temp*temp; 	else 	{ 		if(y > 0) 			return x*temp*temp; 		else 			return (temp*temp)/x; 	} } int main() { 	float x = 2; 	int y = -3; 	printf("%f",  power(x,  y)); 	return 0; }`
 A Error B 1/4 C 4 D 0.25
Question 10 Explanation:
The given code is capable of handling negative powers too. Thus, the output will be 2-2 = 0.25.

There are 10 questions to complete.