So in python, all I have to do is
print(3**4)
Which gives me 81
How do I do this in C? I searched a bit and say the exp()
function, but have no clue how to use it, thanks in advance
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.
To calculate a power in C, the best way is to use the function pow() . It takes two double arguments: the first is the number that will be raised by the power, and the second argument is the power amount itself. So: double z = pow(double x, double y); Then the result will be saved into the double z.
You need pow();
function from math.h
header.
syntax
#include <math.h> double pow(double x, double y); float powf(float x, float y); long double powl(long double x, long double y);
Here x is base and y is exponent. result is x^y
.
usage
pow(2,4); result is 2^4 = 16. //this is math notation only // In c ^ is a bitwise operator
And make sure you include math.h
to avoid warning ("incompatible implicit declaration of built in function 'pow'
").
Link math library by using -lm
while compiling. This is dependent on Your environment.
For example if you use Windows it's not required to do so, but it is in UNIX based systems.
you can use pow(base, exponent)
from #include <math.h>
or create your own:
int myPow(int x,int n) { int i; /* Variable used in loop counter */ int number = 1; for (i = 0; i < n; ++i) number *= x; return(number); }
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