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

31 May, 2022
Given an integer x and a positive number y, write a function that computes xy under following conditions. a) Time complexity of the function should be O(Log y) b) Extra Space is O(1) 
Examples: 
Input: x = 3, y = 5
Output: 243

Input: x = 2, y = 5
Output: 32
 
We have discussed recursive O(Log y) solution for power. The recursive solutions are generally not preferred as they require space on call stack and they involve function call overhead. 
Following is implementation to compute xy.  
C++
C
Java
Python3
C#
PHP
Javascript
// Iterative C program to implement pow(x, n)#include <iostream>using namespace std; /* Iterative Function to calculate (x^y) in O(logy) */int power(int x, unsigned int y){    int res = 1; // Initialize result     while (y > 0) {        // If y is odd, multiply x with result        if (y & 1)            res = res * x;         // y must be even now        y = y >> 1; // y = y/2        x = x * x; // Change x to x^2    }    return res;} // Driver program to test above functionsint main(){    int x = 3;    unsigned int y = 5;     cout<<"Power is "<<power(x, y);     return 0;} // this code is contributed by shivanisinghss2110
// Iterative C++ program to implement pow(x, n)#include <stdio.h> /* Iterative Function to calculate (x^y) in O(logy) */int power(int x, unsigned int y){    int res = 1; // Initialize result     while (y > 0) {        // If y is odd, multiply x with result        if (y & 1)            res = res * x;         // y must be even now        y = y >> 1; // y = y/2        x = x * x; // Change x to x^2    }    return res;} // Driver program to test above functionsint main(){    int x = 3;    unsigned int y = 5;     printf("Power is %d", power(x, y));     return 0;}
// Iterative Java program// to implement pow(x, n)import java.io.*; class GFG{     /* Iterative Function tocalculate (x^y) in O(logy) */static int power(int x, int y){    // Initialize result    int res = 1;     while (y > 0)    {        // If y is odd,        // multiply        // x with result        if ((y & 1) == 1)            res = res * x;         // y must be even now        y = y >> 1; // y = y/2        x = x * x; // Change x to x^2    }    return res;} // Driver Codepublic static void main (String[] args){    int x = 3;    int y = 5;     System.out.println("Power is " +                        power(x, y));}} // This code is contributed// by aj_36
# Iterative Python3 program# to implement pow(x, n) # Iterative Function to# calculate (x^y) in O(logy)def power(x, y):     # Initialize result    res = 1         while (y > 0):                 # If y is odd, multiply        # x with result        if ((y & 1) == 1) :            res = res * x         # y must be even        # now y = y/2        y = y >> 1                 # Change x to x^2        x = x * x         return res  # Driver Codex = 3y = 5 print("Power is ",       power(x, y)) # This code is contributed# by ihritik
// Iterative C# program// to implement pow(x, n)using System; class GFG{     /* Iterative Function tocalculate (x^y) in O(logy) */static int power(int x, int y){    int res = 1; // Initialize result     while (y > 0)    {        // If y is odd, multiply        // x with result        if ((y & 1) == 1)            res = res * x;         // y must be even now        y = y >> 1; // y = y/2        x = x * x; // Change x to x^2    }    return res;} // Driver Codestatic public void Main (){int x = 3;int y = 5; Console.WriteLine("Power is "+                   power(x, y));}} // This code is contributed// by aj_36
<?php// Iterative php program// to implement pow(x, n)> // Iterative Function to// calculate (x^y) in O(logy) function power($x, $y){         // Initialize result    $res = 1;         while ($y > 0)    {                 // If y is odd, multiply        // x with result        if ($y & 1)            $res = $res * $x;         // y must be even now                 // y = y/2        $y = $y >> 1;                 // Change x to x^2        $x = $x * $x;    }    return $res;}     // Driver Code    $x = 3;    $y = 5;     echo "Power is ", power($x, $y); // This code is contributed by ajit?>
<script> // Iterative Javascript program to implement pow(x, n) /* Iterative Function to calculate (x^y) in O(logy) */function power(x, y){// Initialize result    let res = 1;     while (y > 0) {        // If y is odd, multiply x with result        if (y & 1)            res = res * x;         // y must be even now        y = y >> 1; // y = y/2        x = x * x; // Change x to x^2    }    return res;} // Driver program to test above functions      let x = 3;    y = 5;     document.write("Power is " + power(x, y));      // This code is contributed by Mayank Tyagi </script>
Output: 
Power is 243
Time Complexity: O(log y), since in loop each time the value of y decreases by half it’s current value.
Auxiliary Space: O(1), since no extra space has been taken.
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=2a_Snu8qjko" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Udit Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
jit_t
ihritik
mayanktyagi1709
rajpriyam
shivanisinghss2110
subham348
rishavnitro
MakeMyTrip
Mathematical
MakeMyTrip
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.