7 Nov 2020

4.7 Compute x to power of y while x is double and y is integer

Problem: Write a program that takes a double x and an integer y and returns x to power of y. You can ignore overflow and underflow.

def power(x,y):
  if y < 0:
    x = 1.0/x
    y = -y
  result, base = 1, x
  while y:
    if y & 1:
      result *= base
    base = base * base
  return result

Tags: