Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Writing Power Recursively and Iteratively

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Writing Power Recursively and Iteratively. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Brady software may repeatedly calculate scaling factors for label layouts and print configurations. Implement exponentiation for a number and an integer exponent using both recursive and non-recursive approaches, and avoid multiplying once per exponent value.

Return base^exponent using exponentiation by squaring. Your implementation must support positive, zero, and negative exponents. Provide these functions:

  1. power_recursive(base, exponent), using recursive exponentiation by squaring.
  2. power_iterative(base, exponent), using an iterative binary-exponentiation loop.
  3. power(base, exponent), which returns the result using your recursive implementation.

For negative exponents, return the reciprocal of the corresponding positive power. Inputs are chosen so that the result is exactly representable for integer exponents, or normal Python floating-point behavior is acceptable for negative exponents.

Formal Specification

  • Input: base, an integer, and exponent, an integer.
  • Output: A numeric value equal to base^exponent. Positive exponents and zero should return an integer when mathematically integral; negative exponents may return a float.
  • Invalid input: base == 0 with a negative exponent will not appear.

Constraints

  • -10^9 <= base <= 10^9
  • -10^9 <= exponent <= 10^9
  • base and exponent are integers
  • base == 0 with exponent < 0 is excluded

Function Signature

def power(base, exponent):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output