

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Find number of pairs (x, y) in an array such that x^y > y^x in C++
- Find larger of x^y and y^x in C++
- Count of pairs (x, y) in an array such that x < y in C++
- Find maximum among x^(y^2) or y^(x^2) where x and y are given in C++
- Count Distinct Non-Negative Integer Pairs (x, y) that Satisfy the Inequality x*x + y*y < n in C++
- Count Distinct Non-Negative Integer Pairs (x, y) that Satisfy the Inequality x*x + y*y < n in C++
- Find a distinct pair (x, y) in given range such that x divides y in C++
- Find x, y, z that satisfy 2/n = 1/x + 1/y + 1/z in C++
- Write a power (pow) function using C++
- Python Scatter Plot with Multiple Y values for each X
- Check if a number can be expressed as x^y (x raised to power y) in C++
- Write a program to calculate pow(x,n) in C++
- Find the value of the function Y = (X^6 + X^2 + 9894845) % 981 in C++
- What is ternary operator (? X : Y) in C++?
- Pow(x, n) in Python
Advertisements