My question is how do I compute 2^(x) in c. I know there is something like shifting that does the same thing. I tried to do total = x << 1, but that didn't work. I know that if i shift one bit it is the same as multiplying it by two. Or something like that.
int x;
for(x=0; x<4; x++){
total += x <<1; //
}
When this is done executing I expect the total to be 15 ( 20 + 21 + 22 + 23 )
Any ideas on what I am doing wrong? my total starts off as being 0 and then messes up.
Thanks!
It's the other way around. 1 << x
will give you '2 ^ x'.
This should do what you want. Call pow(2, x)
to get 2x.
int abs (int x) {
if (x < 0) return -x;
return x;
}
int signum (int x) {
if (x < 0) return -1;
if (x > 0) return 1;
return 0;
}
int add (int x, int y) {
for (int i = 0; i < abs(y); ++i) {
if (y > 0) ++x;
else --x;
}
return x;
}
int mult (int x, int y) {
int sign = signum(x) * signum(y);
x = abs(x);
y = abs(y);
int res = 0;
for (int i = 0; i < y; ++i) {
res = add(res, x);
}
return sign * res;
}
int pow (int x, int y) {
if (y < 0) return 0;
int res = 1;
for (int i = 0; i < y; ++i) {
res = mult(res, x);
}
return res;
}
Left shift is limited to the word size of your CPU, either 32 or 64 bits, which limits the maximum exponent which you can safely use, before the result is undefined (2^31 or 2^63).
The following works for larger exponents but uses floating point arithmetic. If you need exact results you should consider using a infinite precision maths library such as GMP
#include <math.h>
int main() {
double base = 2;
double exponent = 4;
double result = pow(base, exponent);
return 0;
}
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