# YOU CAN DOWNLOAD 200+ SUBJECTS PDF BOOK FOR COMPETITIVE EXAMINATIONS

## 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; }

O(1) | |

O(n) | |

O(log n) | |

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?

Iterative code requires less time | |

Iterative code requires less space | |

Iterative code is more compiler friendly | |

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?

#include <stdio.h> int power(int x, int y) { int res = 1; while (y > 0) { if (y & 1) res = res * | |

#include <stdio.h> int power(int x, int y) { int res = 1; while (y > 0) { if (y && 1 | |

#include <stdio.h> int power(int x, int y) { int res = 1; while (y > 0) { if (y && 1) res = x * | |

#include <stdio.h> 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.

True | |

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; }

Error | |

1/4 | |

4 | |

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.