Write an iterative O(Log y) function for pow(x, y) in C++


In this problem, we are given two integers x and y. Our task is to create a function that will be equivalent to pow(x,y) using an iterative approach that will complete the task in time complexity of 0(Log y).

Let’s take a few examples to understand the problem,

Input

x = 7 , y = 3

Output

343

The iterative function for pow(x,y) will iterate and update the result for odd values of y multiplying it by x and update x to x2 at every iteration.

Program to show the implementation of the solution

Example

 Live Demo

#include <iostream>
using namespace std;
void calcPower(int x, unsigned int y) {
   int result = 1;
   while (y > 0) {
      if (y & 1)
      result *= x;
      y = y >> 1;
      x = x * x;
   }
   cout<<result;
}
int main() {
   int x = 7;
   unsigned int y = 3;
   cout<<x<<" raised to "<<y<<" is ";
   calcPower(x,y);
   return 0;
}

Output

raised to 3 is 343

Updated on: 17-Apr-2020

419 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements