
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Write four solutions for each of the following equations:(i) \( 2 x+y=7 \)(ii) \( \pi x+y=9 \)(iii) \( x=4 y \).
- Find number of pairs (x, y) in an array such that x^y > y^x in C++
- In the figure, $\angle BAD = 78^o, \angle DCF = x^o$ and $\angle DEF = y^o$. Find the values of $x$ and $y$."\n
- Verify : (i) \( x^{3}+y^{3}=(x+y)\left(x^{2}-x y+y^{2}\right) \)(ii) \( x^{3}-y^{3}=(x-y)\left(x^{2}+x y+y^{2}\right) \)
- Factorize:$4(x - y)^2 - 12(x -y) (x + y) + 9(x + y)^2$
- Write a power (pow) function using C++
- Factorize:\( x^{2}+y-x y-x \)
- Subtract $24 x y-10 y-18 x$ from $30 x y +12 y+14 x$
- Count of pairs (x, y) in an array such that x < y in C++
- Factorize:\( x\left(x^{3}-y^{3}\right)+3 x y(x-y) \)
- Simplify: $\frac{x^{-3}-y^{-3}}{x^{-3} y^{-1}+(x y)^{-2}+y^{-1} x^{-3}}$.
- Write the following in the expanded form:\( (\frac{x}{y}+\frac{y}{z}+\frac{z}{x})^{2} \)
- pow() function for complex number in C++
- From the choices given below, choose the equation whose graphs are given in Fig. \( 4.6 \) and Fig. 4.7.For Fig. 4. 6(i) \( y=x \)(ii) \( x+y=0 \)(iii) \( y=2 x \)(iv) \( 2+3 y=7 x \)For Fig. \( 4.7 \)(i) \( y=x+2 \)(ii) \( y=x-2 \)(iii) \( y=-x+2 \)(iv) \( x+2 y=6 \)"\n
- Expand \( (x-y)^{2}-2(x-y)

Advertisements