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.
There are two alternatives here, when we want to count power(a,n) we may write code which is very short and works in O(logn) time, but is recursively and therefore requires creating new stackframe for each call and needs a bit more time than loop iteration. So short code is:
and as for the faster code, here it is using while loop:
A nice recursive approach you can show off:
C++ standard doesn't have
int pow(int, int)
(It hasdouble pow(double, int)
,float ...
). Microsoft's cmath uses C math.h that has not ipow. Some cmath headers define template version ofpow
.Search for function:ipow lang:c++ on Google Code .
Here's example from the first link:
See calculating integer powers (squares, cubes, etc.) in C++ code.
Binary powering, aka exponentiation by squaring.
Note that this returns 1 for powi(0,0).
A better recursive approach than Zed's.
Much better complexity there O(log²(p)) instead of O(p).
I assume your homework assignment is to write an integral exponent function. First, take a look at what an exponent is:
http://en.wikipedia.org/wiki/Exponent
Then, look in your textbook for how to multiply numbers in C. You'll want to use a
for
loop.