Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

power of an integer in c++ [duplicate]

Tags:

c++

mingw

I need to get the result from pow(a,b) as an integer (both a and b are integers too). currently the calculations where (int) pow( (double)a, (double)b) is included are wrong. Maybe someone can help with a function that does the pow(a,b) with integers and returns an integer too?

But here is the odd part: I made my script in Linux with Geany (and g++/gcc compiler) and had just pow(a,b) the script compiled and worked fine. But in university I have Dev-C++ (and MS Windows). In Dev-C++ the script didn't compile with an error [Warning] converting toint' from double'

I need to make this scrpit work under Windows (and Mingw compiler) too.

like image 247
skazhy Avatar asked Oct 01 '09 18:10

skazhy


People also ask

How do you write a 2 raise power in C?

Syntax: double pow(double x, double y);

Does POW return a double?

The pow() function returns the value x y x^y xy (x raised to the power y) where x and y are two variables of type double. The return type is double.

How do you determine if a number is a power of 2 in C?

Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.

How do you use POW INT?

int intResult = (int) Math. pow(2, 3); The output will be 8. Please note that the int casting in the above example is required if we want to have an Integer result.


1 Answers

A better recursive approach than Zed's.

int myPow(int x, unsigned int p)
{
  if (p == 0) return 1;
  if (p == 1) return x;
  
  int tmp = myPow(x, p/2);
  if (p%2 == 0) return tmp * tmp;
  else return x * tmp * tmp;
}

Much better complexity there O(log²(p)) instead of O(p).

Or as a constexpr function using c++17.

template <unsigned int p>
int constexpr IntPower(const int x)
{
  if constexpr (p == 0) return 1;
  if constexpr (p == 1) return x;

  int tmp = IntPower<p / 2>(x);
  if constexpr ((p % 2) == 0) { return tmp * tmp; }
  else { return x * tmp * tmp; }
}
like image 151
Matthieu M. Avatar answered Oct 02 '22 08:10

Matthieu M.