# 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 1 [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER] |

What will be the output for following code?

#include<stdio.h> int func(int x, int y) { if (y == 0) return 1; else if (y%2 == 0) return func(x, y/2)*func(x, y/2); else return x*func(x, y/2)*func(x, y/2); } int main() { int x = 2; int y = 3; printf("%d", func(x, y)); return 0; }

9 | |

6 | |

8 | |

5 |

Question 1 Explanation:

The given program calculates the value of x raised to power y. Thus 2

^{3}= 8.Question 2 [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER] |

What will be the time complexity of the following code which raises an integer x to the power y?

#include<stdio.h> int power(int x, int y) { if (y == 0) return 1; else if (y%2 == 0) return power(x, y/2)*power(x, y/2); else return x*power(x, y/2)*power(x, y/2); } int main() { int x = 2; int y = 3; printf("%d", power(x, y)); return 0; }

O(n) | |

O(log n) | |

O(n log n) | |

O(n ^{2}) |

Question 2 Explanation:

The recurrence relation for the above code is given by T(n)=2T(n/2)+c. By using master theorem we can calculate the result for this relation. It is found to be equal to O(n).

Question 3 [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER] |

What is the space complexity of the given code?

#include<stdio.h> int power(int x, int y) { if (y == 0) return 1; else if (y%2 == 0) return power(x, y/2)*power(x, y/2); else return x*power(x, y/2)*power(x, y/2); } 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 3 Explanation:

The space complexity of the given code will be equal to O(1) as it uses only constant space in the memory.

Question 4 [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER] |

Recursive program to raise an integer x to power y uses which of the following algorithm?

Dynamic programming | |

Backtracking | |

Divide and conquer | |

Greedy algorithm |

Question 4 Explanation:

The recursive approach uses divide and conquer algorithm as we break the problem into smaller parts and then solve the smaller parts and finally combine their results to get the overall solution.

Question 5 [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER] |

What is the least time in which we can raise a number x to power y?

O(x) | |

O(y) | |

O(log x) | |

O(log y) |

Question 5 Explanation:

We can optimize the code for finding power of a number by calculating x raised to power y/2 only once and using it depending on whether y is even or odd.

There are 5 questions to complete.