Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements