321

What is the most efficient way given to raise an integer to the power of another integer in C?

// 2^3
pow(2,3) == 8
// 5^5
pow(5,5) == 3125
durron597
32.4k18 gold badges104 silver badges162 bronze badges
asked Sep 19, 2008 at 12:30
6
  • 8
    When you say "efficiency," you need to specify efficient in relation to what. Speed? Memory usage? Code size? Maintainability? Commented Oct 2, 2008 at 17:26
  • Doesn't C have a pow() function? Commented May 30, 2009 at 13:07
  • 28
    yes, but that works on floats or doubles, not on ints Commented May 30, 2009 at 13:46
  • 3
    If you're sticking to actual ints (and not some huge-int class), a lot of calls to ipow will overflow. It makes me wonder if there's a clever way to pre-calculate a table and reduce all the non-overflowing combinations to a simple table lookup. This would take more memory than most of the general answers, but perhaps be more efficient in terms of speed. Commented Jan 7, 2016 at 17:15
  • 1
    pow() not a safe function Commented Oct 29, 2017 at 15:42

20 Answers 20

464

Exponentiation by squaring.

int ipow(int base, int exp)
{
 int result = 1;
 for (;;)
 {
 if (exp & 1)
 result *= base;
 exp >>= 1;
 if (!exp)
 break;
 base *= base;
 }
 return result;
}

This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography.

John Zwinck
251k44 gold badges344 silver badges457 bronze badges
answered Sep 19, 2008 at 12:54

20 Comments

You should probably add a check that "exp" isn't negative. Currently, this function will either give a wrong answer or loop forever. (Depending on whether >>= on a signed int does zero-padding or sign-extension - C compilers are allowed to pick either behaviour).
I wrote a more optimized version of this, freely downloadable here: gist.github.com/3551590 On my machine it was about 2.5x faster.
@AkhilJain: It's perfectly good C; to make it valid also in Java, replace while (exp) and if (exp & 1) with while (exp != 0) and if ((exp & 1) != 0) respectively.
Your function should probably have unsigned exp, or else handle negative exp properly.
@ZinanXing Multiplying n times results in more multiplications and is slower. This method saves multiplications by effectively reusing them. E.g., to calculate n^8 the naïve method of n*n*n*n*n*n*n*n uses 7 multiplications. This algorithm instead computes m=n*n, then o=m*m, then p=o*o, where p = n^8, with just three multiplications. With large exponents the difference in performance is significant.
|
98

Note that exponentiation by squaring is not the most optimal method. It is probably the best you can do as a general method that works for all exponent values, but for a specific exponent value there might be a better sequence that needs fewer multiplications.

For instance, if you want to compute x^15, the method of exponentiation by squaring will give you:

x^15 = (x^7)*(x^7)*x 
x^7 = (x^3)*(x^3)*x 
x^3 = x*x*x

This is a total of 6 multiplications.

It turns out this can be done using "just" 5 multiplications via addition-chain exponentiation.

n*n = n^2
n^2*n = n^3
n^3*n^3 = n^6
n^6*n^6 = n^12
n^12*n^3 = n^15

There are no efficient algorithms to find this optimal sequence of multiplications. From Wikipedia:

The problem of finding the shortest addition chain cannot be solved by dynamic programming, because it does not satisfy the assumption of optimal substructure. That is, it is not sufficient to decompose the power into smaller powers, each of which is computed minimally, since the addition chains for the smaller powers may be related (to share computations). For example, in the shortest addition chain for a15 above, the subproblem for a6 must be computed as (a3)2 since a3 is re-used (as opposed to, say, a6 = a2(a2)2, which also requires three multiplies).

answered Sep 20, 2008 at 18:43

6 Comments

@JeremySalwen: As this answer states, binary exponentiation is not in general the most optimal method. There are no efficient algorithms currently known for finding the minimal sequence of multiplications.
@EricPostpischil, That depends on your application. Usually we don't need a general algorithm to work for all numbers. See The Art of Computer Programming, Vol. 2: Seminumerical Algorithms
There's a good exposition of this exact problem in From Mathematics to Generic Programming by Alexander Stepanov and Daniel Rose. This book should be on the shelf of every software practitioner, IMHO.
This could be optimized for integers because there are well under 255 integer powers that will not cause overflow for 32 bit integers. You could cache the optimal multiplication structure for each int. I imagine the code+data would still be smaller than simply caching all powers...
|
33

If you need to raise 2 to a power. The fastest way to do so is to bit shift by the power.

2 ** 3 == 1 << 3 == 8
2 ** 30 == 1 << 30 == 1073741824 (A Gigabyte)
answered Mar 17, 2011 at 21:17

3 Comments

Is there an elegant way to do this so that 2 ** 0 == 1 ?
@RobSmallshire Maybe 2 ** x = 1 << x (as 1<<0 is 1, you'll have to check if it's in the C std, or if it's platform dependant, but you could do also 2 ** x = x ? (1 << x) : 1 note that 2 ** x has a meaning in C, and that's not power :)
Note that 1 << 31 is UB. Consider 1u << 31.
12

Here is the method in Java

private int ipow(int base, int exp)
{
 int result = 1;
 while (exp != 0)
 {
 if ((exp & 1) == 1)
 result *= base;
 exp >>= 1;
 base *= base;
 }
 return result;
}
answered May 9, 2012 at 13:55

6 Comments

does not work for large numbes e.g pow(71045970,41535484)
@AnushreeAcharjee of course not. Computing such a number would require arbitrary precision arithmetic.
Use BigInteger#modPow or Biginteger#pow for big numbers, appropriate algorithms based on size of arguments are already implemented
On the one hand, the question was tagged by the OP as C, so it is clearly a C question. Moreover, these kind of microoptimizations are not usually done in such high level languages (performance is not what you're after, if you use Java, I guess). On the other hand, if this question is high in search engines, it might be interesting to expand it to other languages too. So, never mind my old comment :)
@AnushreeAcharjee : yeah youve also forgotten that 71045970 ^ 41535484 has 326mn digits in decimal
|
9

power() function to work for Integers Only

int power(int base, unsigned int exp){
 if (exp == 0)
 return 1;
 int temp = power(base, exp/2);
 if (exp%2 == 0)
 return temp*temp;
 else
 return base*temp*temp;
}

Complexity = O(log(exp))

power() function to work for negative exp and float base.

float power(float base, int exp) {
 if( exp == 0)
 return 1;
 float temp = power(base, exp/2); 
 if (exp%2 == 0)
 return temp*temp;
 else {
 if(exp > 0)
 return base*temp*temp;
 else
 return (temp*temp)/base; //negative exponent computation 
 }
} 

Complexity = O(log(exp))

answered Jan 7, 2016 at 16:25

4 Comments

How is this different from the answers of Abhijit Gaikwad and chux? Please argue the use of float in the second code block presented (consider showing how power(2.0, -3) gets computed).
@greybeard I have mentioned some comment. may be that can resolve your query
GNU Scientific Library already has your second function: gnu.org/software/gsl/manual/html_node/Small-integer-powers.html
@roottraveller could you please explain negative exp and float base solution? why we use temp, separate exp by 2 and check exp (even/odd)? thanks!
9

An extremely specialized case is, when you need say 2^(-x to the y), where x, is of course is negative and y is too large to do shifting on an int. You can still do 2^x in constant time by screwing with a float.

struct IeeeFloat
{
 unsigned int base : 23;
 unsigned int exponent : 8;
 unsigned int signBit : 1;
};
union IeeeFloatUnion
{
 IeeeFloat brokenOut;
 float f;
};
inline float twoToThe(char exponent)
{
 // notice how the range checking is already done on the exponent var 
 static IeeeFloatUnion u;
 u.f = 2.0;
 // Change the exponent part of the float
 u.brokenOut.exponent += (exponent - 1);
 return (u.f);
}

You can get more powers of 2 by using a double as the base type. (Thanks a lot to commenters for helping to square this post away).

There's also the possibility that learning more about IEEE floats, other special cases of exponentiation might present themselves.

10 Comments

Nifty solution, but unsigend??
An IEEE float is base x 2 ^ exp, changing the exponent value won't lead to anything else than a multiplication by a power of two, and chances are high it will denormalize the float ... your solution is wrong IMHO
You are all correct, I misremembered that my solution was originally written, oh so long ago, for powers of 2 explicitly. I've rewritten my answer to be a special case solution to the problem.
Firstly, the code is broken as quoted, and requires editing to get it to compile. Secondly the code is broken on a core2d using gcc. see this dump Perhaps I did something wrong. I however do not think this will work, since the IEEE float exponent is base 10.
Base 10? Uh no, it's base 2, unless you meant 10 in binary :)
|
6

If you want to get the value of an integer for 2 raised to the power of something it is always better to use the shift option:

pow(2,5) can be replaced by 1<<5

This is much more efficient.

Kevin Bedell
13.5k10 gold badges80 silver badges116 bronze badges
answered May 14, 2012 at 7:03

Comments

5
int pow( int base, int exponent)
{ // Does not work for negative exponents. (But that would be leaving the range of int) 
 if (exponent == 0) return 1; // base case;
 int temp = pow(base, exponent/2);
 if (exponent % 2 == 0)
 return temp * temp; 
 else
 return (base * temp * temp);
}
answered Sep 19, 2008 at 14:34

2 Comments

Not my vote, but pow(1, -1) doesn't leave the range of int despite a negative exponent. Now that one works by accident, as does pow(-1, -1).
The only negative exponent that may not make you leave the range of int is -1. And it only works if base is 1 or -1. So there are only two pairs (base,exp) with exp<0 that would not lead to non integer powers. Although I'm a matematician and I like quantifiers, I think in this case, in practice, it's ok to say that a negative exponent makes you leave the integer realm...
4

Just as a follow up to comments on the efficiency of exponentiation by squaring.

The advantage of that approach is that it runs in log(n) time. For example, if you were going to calculate something huge, such as x^1048575 (2^20 - 1), you only have to go thru the loop 20 times, not 1 million+ using the naive approach.

Also, in terms of code complexity, it is simpler than trying to find the most optimal sequence of multiplications, a la Pramod's suggestion.

Edit:

I guess I should clarify before someone tags me for the potential for overflow. This approach assumes that you have some sort of hugeint library.

answered Oct 2, 2008 at 17:39

Comments

4

Late to the party:

Below is a solution that also deals with y < 0 as best as it can.

  1. It uses a result of intmax_t for maximum range. There is no provision for answers that do not fit in intmax_t.
  2. powjii(0, 0) --> 1 which is a common result for this case.
  3. pow(0,negative), another undefined result, returns INTMAX_MAX

    intmax_t powjii(int x, int y) {
     if (y < 0) {
     switch (x) {
     case 0:
     return INTMAX_MAX;
     case 1:
     return 1;
     case -1:
     return y % 2 ? -1 : 1;
     }
     return 0;
     }
     intmax_t z = 1;
     intmax_t base = x;
     for (;;) {
     if (y % 2) {
     z *= base;
     }
     y /= 2;
     if (y == 0) {
     break; 
     }
     base *= base;
     }
     return z;
    }
    

This code uses a forever loop for(;;) to avoid the final base *= base common in other looped solutions. That multiplication is 1) not needed and 2) could be int*int overflow which is UB.

answered Apr 1, 2015 at 17:11

3 Comments

powjii(INT_MAX, 63) causes UB in base *= base. Consider checking that you can multiply, or move to unsigned and let it wrap around.
There is no reason to have exp be signed. It complicates the code because of the odd situation where (-1) ** (-N) is valid, and any abs(base) > 1 will be 0 for negative values of exp, so it is better to have it unsigned and save that code.
@CacahueteFrito True that y as signed is not really needed and brings the complications you commented on, yet OP's request was specific pow(int, int). Thus those good comments belong with the OP's question. As OP has not specified what to do on overflow, a well defined wrong answer is only marginally better than UB. Given "most efficient way", I doubt OP cares about OF.
3

In addition to the answer by Elias, which causes Undefined Behaviour when implemented with signed integers, and incorrect values for high input when implemented with unsigned integers,

here is a modified version of the Exponentiation by Squaring that also works with signed integer types, and doesn't give incorrect values:

#include <stdint.h>
#define SQRT_INT64_MAX (INT64_C(0xB504F333))
int64_t alx_pow_s64 (int64_t base, uint8_t exp)
{
 int_fast64_t base_;
 int_fast64_t result;
 base_ = base;
 if (base_ == 1)
 return 1;
 if (!exp)
 return 1;
 if (!base_)
 return 0;
 result = 1;
 if (exp & 1)
 result *= base_;
 exp >>= 1;
 while (exp) {
 if (base_ > SQRT_INT64_MAX)
 return 0;
 base_ *= base_;
 if (exp & 1)
 result *= base_;
 exp >>= 1;
 }
 return result;
}

Considerations for this function:

(1 ** N) == 1
(N ** 0) == 1
(0 ** 0) == 1
(0 ** N) == 0

If any overflow or wrapping is going to take place, return 0;

I used int64_t, but any width (signed or unsigned) can be used with little modification. However, if you need to use a non-fixed-width integer type, you will need to change SQRT_INT64_MAX by (int)sqrt(INT_MAX) (in the case of using int) or something similar, which should be optimized, but it is uglier, and not a C constant expression. Also casting the result of sqrt() to an int is not very good because of floating point precission in case of a perfect square, but as I don't know of any implementation where INT_MAX -or the maximum of any type- is a perfect square, you can live with that.

answered Mar 17, 2019 at 19:17

Comments

2

The O(log N) solution in Swift...

// Time complexity is O(log N)
func power(_ base: Int, _ exp: Int) -> Int { 
 // 1. If the exponent is 1 then return the number (e.g a^1 == a)
 //Time complexity O(1)
 if exp == 1 { 
 return base
 }
 // 2. Calculate the value of the number raised to half of the exponent. This will be used to calculate the final answer by squaring the result (e.g a^2n == (a^n)^2 == a^n * a^n). The idea is that we can do half the amount of work by obtaining a^n and multiplying the result by itself to get a^2n
 //Time complexity O(log N)
 let tempVal = power(base, exp/2) 
 // 3. If the exponent was odd then decompose the result in such a way that it allows you to divide the exponent in two (e.g. a^(2n+1) == a^1 * a^2n == a^1 * a^n * a^n). If the eponent is even then the result must be the base raised to half the exponent squared (e.g. a^2n == a^n * a^n = (a^n)^2).
 //Time complexity O(1)
 return (exp % 2 == 1 ? base : 1) * tempVal * tempVal 
}
answered May 4, 2021 at 0:30

Comments

2
int pow(int const x, unsigned const e) noexcept
{
 return !e ? 1 : 1 == e ? x : (e % 2 ? x : 1) * pow(x * x, e / 2);
 //return !e ? 1 : 1 == e ? x : (((x ^ 1) & -(e % 2)) ^ 1) * pow(x * x, e / 2);
}

Yes, it's recursive, but a good optimizing compiler will optimize recursion away.

answered May 5, 2021 at 23:54

4 Comments

Clang does optimize the tail recursion, but gcc doesn't unless you replace order of multiplication i.e. (e % 2 ? x : 1) * pow(x * x, e / 2) godbolt.org/z/EoWbfx5nc
@Andy I did notice gcc was struggling, but I don't mind, since I'm using this function as a constexpr function.
for the love of god, don't write code in answers like this, you are being too clever for your own good (and the good of others). you have compressed 3 conditions and one loop in a single line, making the code effectively obfuscated (and unreadable by anybody that hopes to understand what you mean).
this is ok for a consteval or a constexprfunction.
1

more generic solution considering negative exponenet

private static int pow(int base, int exponent) {
 int result = 1;
 if (exponent == 0)
 return result; // base case;
 if (exponent < 0)
 return 1 / pow(base, -exponent);
 int temp = pow(base, exponent / 2);
 if (exponent % 2 == 0)
 return temp * temp;
 else
 return (base * temp * temp);
}
answered Jun 19, 2014 at 5:30

4 Comments

integer division results in an integer, so your negative exponent could be a lot more efficient since it'll only return 0, 1, or -1...
pow(i, INT_MIN) could be an infinite loop.
@chux: It could format your harddisk: integer overflow is UB.
@MSalters pow(i, INT_MIN) is not integer overflow. The assignment of that result to temp certainly may overflow, potential causing the end of time, but I'll settle for a seemingly random value. :-)
1

Here is a O(1) algorithm for calculating x ** y, inspired by this comment. It works for 32-bit signed int.

For small values of y, it uses exponentiation by squaring. For large values of y, there are only a few values of x where the result doesn't overflow. This implementation uses a lookup table to read the result without calculating.

On overflow, the C standard permits any behavior, including crash. However, I decided to do bound-checking on LUT indices to prevent memory access violation, which could be surprising and undesirable.

Pseudo-code:

If `x` is between -2 and 2, use special-case formulas.
Otherwise, if `y` is between 0 and 8, use special-case formulas.
Otherwise:
 Set x = abs(x); remember if x was negative
 If x <= 10 and y <= 19:
 Load precomputed result from a lookup table
 Otherwise:
 Set result to 0 (overflow)
 If x was negative and y is odd, negate the result

C code:

#define POW9(x) x * x * x * x * x * x * x * x * x
#define POW10(x) POW9(x) * x
#define POW11(x) POW10(x) * x
#define POW12(x) POW11(x) * x
#define POW13(x) POW12(x) * x
#define POW14(x) POW13(x) * x
#define POW15(x) POW14(x) * x
#define POW16(x) POW15(x) * x
#define POW17(x) POW16(x) * x
#define POW18(x) POW17(x) * x
#define POW19(x) POW18(x) * x
int mypow(int x, unsigned y)
{
 static int table[8][11] = {
 {POW9(3), POW10(3), POW11(3), POW12(3), POW13(3), POW14(3), POW15(3), POW16(3), POW17(3), POW18(3), POW19(3)},
 {POW9(4), POW10(4), POW11(4), POW12(4), POW13(4), POW14(4), POW15(4), 0, 0, 0, 0},
 {POW9(5), POW10(5), POW11(5), POW12(5), POW13(5), 0, 0, 0, 0, 0, 0},
 {POW9(6), POW10(6), POW11(6), 0, 0, 0, 0, 0, 0, 0, 0},
 {POW9(7), POW10(7), POW11(7), 0, 0, 0, 0, 0, 0, 0, 0},
 {POW9(8), POW10(8), 0, 0, 0, 0, 0, 0, 0, 0, 0},
 {POW9(9), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
 {POW9(10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
 };
 int is_neg;
 int r;
 switch (x)
 {
 case 0:
 return y == 0 ? 1 : 0;
 case 1:
 return 1;
 case -1:
 return y % 2 == 0 ? 1 : -1;
 case 2:
 return 1 << y;
 case -2:
 return (y % 2 == 0 ? 1 : -1) << y;
 default:
 switch (y)
 {
 case 0:
 return 1;
 case 1:
 return x;
 case 2:
 return x * x;
 case 3:
 return x * x * x;
 case 4:
 r = x * x;
 return r * r;
 case 5:
 r = x * x;
 return r * r * x;
 case 6:
 r = x * x;
 return r * r * r;
 case 7:
 r = x * x;
 return r * r * r * x;
 case 8:
 r = x * x;
 r = r * r;
 return r * r;
 default:
 is_neg = x < 0;
 if (is_neg)
 x = -x;
 if (x <= 10 && y <= 19)
 r = table[x - 3][y - 9];
 else
 r = 0;
 if (is_neg && y % 2 == 1)
 r = -r;
 return r;
 }
 }
}
answered Jul 7, 2022 at 20:58

Comments

0

One more implementation (in Java). May not be most efficient solution but # of iterations is same as that of Exponential solution.

public static long pow(long base, long exp){ 
 if(exp ==0){
 return 1;
 }
 if(exp ==1){
 return base;
 }
 if(exp % 2 == 0){
 long half = pow(base, exp/2);
 return half * half;
 }else{
 long half = pow(base, (exp -1)/2);
 return base * half * half;
 } 
}
answered Dec 27, 2013 at 21:24

1 Comment

Not a Java question!
0

I use recursive, if the exp is even,5^10 =25^5.

int pow(float base,float exp){
 if (exp==0)return 1;
 else if(exp>0&&exp%2==0){
 return pow(base*base,exp/2);
 }else if (exp>0&&exp%2!=0){
 return base*pow(base,exp-1);
 }
}
answered Feb 3, 2015 at 14:36

Comments

0

I have implemented algorithm that memorizes all computed powers and then uses them when need. So for example x^13 is equal to (x^2)^2^2 * x^2^2 * x where x^2^2 it taken from the table instead of computing it once again. This is basically implementation of @Pramod answer (but in C#). The number of multiplication needed is Ceil(Log n)

public static int Power(int base, int exp)
{
 int tab[] = new int[exp + 1];
 tab[0] = 1;
 tab[1] = base;
 return Power(base, exp, tab);
}
public static int Power(int base, int exp, int tab[])
 {
 if(exp == 0) return 1;
 if(exp == 1) return base;
 int i = 1;
 while(i < exp/2)
 { 
 if(tab[2 * i] <= 0)
 tab[2 * i] = tab[i] * tab[i];
 i = i << 1;
 }
 if(exp <= i)
 return tab[i];
 else return tab[i] * Power(base, exp - i, tab);
}
answered Aug 12, 2015 at 21:16

1 Comment

public? 2 functions named the same? This is a C question.
-1

My case is a little different, I'm trying to create a mask from a power, but I thought I'd share the solution I found anyway.

Obviously, it only works for powers of 2.

Mask1 = 1 << (Exponent - 1);
Mask2 = Mask1 - 1;
return Mask1 + Mask2;
answered Aug 16, 2016 at 20:55

9 Comments

I tried that, it doesn't work for 64 bit, it's shifted off never to return, and in this specific case, I'm trying to set all bits lower than X, inclusive.
Was that for 1 << 64 ? That's an overflow. The largest integer is just below that: (1 << 64) - 1.
1 << 64 == 0, that's why. Maybe your representation is best for your app. I prefer stuff that can be put in a macro, without an extra variable, like #define MASK(e) (((e) >= 64) ? -1 :( (1 << (e)) - 1)), so that can be computed at compile time
Yes, i know what an overflow is. Just because i didm't use that word isn't an invitation to be needlessly condescending. As i said, this works for me and it took a bit of effort to discover hence sharing it. It's that simple.
I'm sorry if I offended you. I truly didn't mean to.
|
-1

In case you know the exponent (and it is an integer) at compile-time, you can use templates to unroll the loop. This can be made more efficient, but I wanted to demonstrate the basic principle here:

#include <iostream>
template<unsigned long N>
unsigned long inline exp_unroll(unsigned base) {
 return base * exp_unroll<N-1>(base);
}

We terminate the recursion using a template specialization:

template<>
unsigned long inline exp_unroll<1>(unsigned base) {
 return base;
}

The exponent needs to be known at runtime,

int main(int argc, char * argv[]) {
 std::cout << argv[1] <<"**5= " << exp_unroll<5>(atoi(argv[1])) << ;std::endl;
}
answered Apr 7, 2018 at 23:29

1 Comment

This is clearly not a C++ question. (c != c++) == 1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.