Write you own Power without using multiplication(*) and division(/) operators

11 Jun, 2022
Method 1 (Using Nested Loops)We can calculate power by using repeated addition. For example to calculate 5^6. 1) First 5 times add 5, we get 25. (5^2) 2) Then 5 times add 25, we get 125. (5^3) 3) Then 5 times add 125, we get 625 (5^4) 4) Then 5 times add 625, we get 3125 (5^5) 5) Then 5 times add 3125, we get 15625 (5^6) 
C++
C
Java
Python
C#
PHP
Javascript
// C++ code for power function#include <bits/stdc++.h>using namespace std; /* Works only if a >= 0 and b >= 0 */int pow(int a, int b){    if (b == 0)        return 1;    int answer = a;    int increment = a;    int i, j;    for(i = 1; i < b; i++)    {        for(j = 1; j < a; j++)        {            answer += increment;        }        increment = answer;    }    return answer;} // Driver Codeint main(){    cout << pow(5, 3);    return 0;} // This code is contributed// by rathbhupendra
#include<stdio.h>/* Works only if a >= 0 and b >= 0  */int pow(int a, int b){  //base case : anything raised to the power 0 is 1  if (b == 0)    return 1;  int answer = a;  int increment = a;  int i, j;  for(i = 1; i < b; i++)  {     for(j = 1; j < a; j++)     {        answer += increment;     }     increment = answer;  }  return answer;} /* driver program to test above function */int main(){  printf("\n %d", pow(5, 3));  getchar();  return 0;}
import java.io.*; class GFG {         /* Works only if a >= 0 and b >= 0 */    static int pow(int a, int b)    {        if (b == 0)            return 1;                     int answer = a;        int increment = a;        int i, j;                 for (i = 1; i < b; i++) {            for (j = 1; j < a; j++) {                answer += increment;            }            increment = answer;        }                 return answer;    }     // driver program to test above function    public static void main(String[] args)    {        System.out.println(pow(5, 3));    }} // This code is contributed by vt_m.
# Python 3 code for power# function # Works only if a >= 0 and b >= 0def pow(a,b):    if(b==0):        return 1             answer=a    increment=a         for i in range(1,b):        for j in range (1,a):            answer+=increment        increment=answer    return answer # driver codeprint(pow(5,3)) # this code is contributed# by Sam007
using System; class GFG{    /* Works only if a >= 0 and b >= 0 */    static int pow(int a, int b)    {        if (b == 0)            return 1;                     int answer = a;        int increment = a;        int i, j;                 for (i = 1; i < b; i++) {            for (j = 1; j < a; j++) {                answer += increment;            }            increment = answer;        }                 return answer;    }     // driver program to test    // above function    public static void Main()    {        Console.Write(pow(5, 3));    }} // This code is contributed by Sam007
<?php // Works only if a >= 0// and b >= 0function poww($a, $b){    if ($b == 0)        return 1;    $answer = $a;    $increment = $a;    $i;    $j;    for($i = 1; $i < $b; $i++)    {        for($j = 1; $j < $a; $j++)        {            $answer += $increment;        }        $increment = $answer;    }    return $answer;}     // Driver Code    echo( poww(5, 3));  // This code is contributed by nitin mittal.?>
<script>    /* Works only if a >= 0 and b >= 0 */function pow(a , b){    if (b == 0)        return 1;             var answer = a;    var increment = a;    var i, j;         for (i = 1; i < b; i++)    {        for (j = 1; j < a; j++)        {            answer += increment;        }        increment = answer;    }         return answer;} // driver program to test above functiondocument.write(pow(5, 3)); // This code is contributed by shikhasingrajput</script>
Output : 
125
Time Complexity: O(a * b)
Auxiliary Space: O(1)
Method 2 (Using Recursion) Recursively add a to get the multiplication of two numbers. And recursively multiply to get a raise to the power b.
C++
C
Java
Python3
C#
PHP
Javascript
#include<bits/stdc++.h>using namespace std; /* A recursive function to get x*y */int multiply(int x, int y){    if(y)        return (x + multiply(x, y - 1));    else        return 0;} /* A recursive function to get a^bWorks only if a >= 0 and b >= 0 */int pow(int a, int b){    if(b)        return multiply(a, pow(a, b - 1));    else        return 1;} // Driver Codeint main(){    cout << pow(5, 3);    getchar();    return 0;} // This code is contributed// by Akanksha Rai
#include<stdio.h>/* A recursive function to get a^b  Works only if a >= 0 and b >= 0  */int pow(int a, int b){   if(b)     return multiply(a, pow(a, b-1));   else    return 1;}    /* A recursive function to get x*y */int multiply(int x, int y){   if(y)     return (x + multiply(x, y-1));   else     return 0;} /* driver program to test above functions */int main(){  printf("\n %d", pow(5, 3));  getchar();  return 0;}
import java.io.*; class GFG {         /* A recursive function to get a^b    Works only if a >= 0 and b >= 0 */    static int pow(int a, int b)    {                 if (b > 0)            return multiply(a, pow(a, b - 1));        else            return 1;    }     /* A recursive function to get x*y */    static int multiply(int x, int y)    {                 if (y > 0)            return (x + multiply(x, y - 1));        else            return 0;    }     /* driver program to test above functions */    public static void main(String[] args)    {        System.out.println(pow(5, 3));    }} // This code is contributed by vt_m.
def pow(a,b):         if(b):        return multiply(a, pow(a, b-1));    else:        return 1;      # A recursive function to get x*y *def multiply(x, y):         if (y):        return (x + multiply(x, y-1));    else:        return 0; # driver program to test above functions *print(pow(5, 3));  # This code is contributed# by Sam007
using System; class GFG{    /* A recursive function to get a^b    Works only if a >= 0 and b >= 0 */    static int pow(int a, int b)    {                 if (b > 0)            return multiply(a, pow(a, b - 1));        else            return 1;    }     /* A recursive function to get x*y */    static int multiply(int x, int y)    {                 if (y > 0)            return (x + multiply(x, y - 1));        else            return 0;    }     /* driver program to test above functions */    public static void Main()    {        Console.Write(pow(5, 3));    }} // This code is contributed by Sam007
<?php /* A recursive function to get a^b   Works only if a >= 0 and b >= 0 */function p_ow( $a, $b){    if($b)        return multiply($a,          p_ow($a, $b - 1));    else        return 1;} /* A recursive function   to get x*y */function multiply($x, $y){    if($y)        return ($x + multiply($x, $y - 1));    else        return 0;} // Driver Codeecho pow(5, 3); // This code is contributed by anuj_67.?>
<script> // A recursive function to get a^b// Works only if a >= 0 and b >= 0function pow(a, b){    if (b > 0)        return multiply(a, pow(a, b - 1));    else        return 1;} // A recursive function to get x*yfunction multiply(x, y){    if (y > 0)        return (x + multiply(x, y - 1));    else        return 0;} // Driver codedocument.write(pow(5, 3)); // This code is contributed by gauravrajput1 </script>
Output : 
125
Time Complexity: O(b)
Auxiliary Space: O(b) 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Method 3 (Using bit masking) 
approach
we can a^n (let’s say 3^5) as 3^4 * 3^0 * 3^1 = 3^, so we can represent 5 as its binary i.e. 101
t
C++
C
Java
Python3
C#
Javascript
#include <iostream>using namespace std; //function calculating powerlong long pow(int a, int n){    int ans=1;      while(n>0){          // calculate last bit(right most) bit of n        int last_bit = n&1;                     //if last bit is 1 then multiply ans and a          if(last_bit){            ans = ans*a;        }             //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8      a = a*a;      n = n >> 1;    }      return ans;} //driver codeint main() {     cout<<pow(3,5);    return 0;}
#include <stdio.h> // function calculating powerlong long pow_(int a, int n){  int ans = 1;  while(n > 0)  {         // calculate last bit(right most) bit of n    int last_bit = n&1;     // if last bit is 1 then multiply ans and a    if(last_bit){      ans = ans*a;    }     //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8    a = a*a;    n = n >> 1;  }  return ans;} // driver codeint main(){   // pow is an inbuilt function so I have used pow_ as a function name  printf("%lld",pow_(3,5));  return 0;} // This code is contributed by akashish_.
// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // function calculating powerstatic int pow(int a, int n){    int ans = 1;      while(n > 0)      {                   // calculate last bit(right most) bit of n        int last_bit = n&1;                      //if last bit is 1 then multiply ans and a          if(last_bit != 0){            ans = ans*a;        }              //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8      a = a*a;      n = n >> 1;    }      return ans;} // Driver Codepublic static void main(String[] args){    System.out.print(pow(3,5));}} // This code is contributed by code_hunt.
# function calculating powerdef pow(a, n):    ans = 1    while(n > 0):               #  calculate last bit(right most) bit of n        last_bit = n&1                   # if last bit is 1 then multiply ans and a        if(last_bit):            ans = ans*a               # make a equal to square of a as on        # every succeeding bit it got squared        # like a^0, a^1, a^2, a^4, a^8        a = a*a        n = n >> 1    return ans # driver codeprint(pow(3, 5)) # This code is contributed by shinjanpatra
// C# code to implement the approachusing System;using System.Numerics;using System.Collections.Generic; public class GFG { // function calculating powerstatic int pow(int a, int n){    int ans = 1;      while(n > 0)      {                   // calculate last bit(right most) bit of n        int last_bit = n&1;                      //if last bit is 1 then multiply ans and a          if(last_bit != 0){            ans = ans*a;        }              //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8      a = a*a;      n = n >> 1;    }      return ans;} // Driver Codepublic static void Main(string[] args){    Console.Write(pow(3,5));}} // This code is contributed by sanjoy_62.
<script> // function calculating powerfunction pow(a, n){    let ans = 1;    while(n > 0)    {             // calculate last bit(right most) bit of n        let last_bit = n&1;                   // if last bit is 1 then multiply ans and a        if(last_bit)        {            ans = ans*a;        }               // make a equal to square of a as on        // every succeeding bit it got squared        // like a^0, a^1, a^2, a^4, a^8        a = a*a;        n = n >> 1;    }    return ans;} // driver codedocument.write(pow(3,5),"</br>"); // This code is contributed by shinjanpatra </script>
Time Complexity: O(log n)
Auxiliary Space: O(1)
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OIgpvFAew6k" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem. 
nitin mittal
vt_m
rathbhupendra
Akanksha_Rai
dkp1903
nidhi_biet
shikhasingrajput
GauravRajput1
subhammahato348
subham348
kkunalguptaaa
shinjanpatra
kashishsoda
sweetyty
sanjoy_62
code_hunt
akashish__
Divide and Conquer
Mathematical
Mathematical
Divide and Conquer
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge Sort
QuickSort
Binary Search
Count Inversions in an array | Set 1 (Using Merge Sort)
Median of two sorted arrays of different sizes
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays