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 to
int' from double'
I need to make this scrpit work under Windows (and Mingw compiler) too.
Syntax: double pow(double x, double y);
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.
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.
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.
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With