How to use boost to degree x in c

My question is how to calculate 2 ^ (x) in c. I know that there is something like a shift 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, I expect the sum to be 15 (2 ^ 0 + 2 ^ 1 +2 ^ 2 + 2 ^ 3)

Any ideas on what I'm doing wrong? my amount starts at 0 and then messy.

Thank!

+5
source share
3 answers

This is the opposite. 1 << xwill give you "2 ^ x".

+22
source

, . pow(2, x), 2 x.

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;
}
+2

The left shift is limited by the word size of your processor, either 32 or 64 bits, which limits the maximum value that you can safely use to an undefined result (2 ^ 31 or 2 ^ 63).

The following works for larger exhibitors, but uses floating point arithmetic. If you need accurate results, you should use a math library with infinite precision, such as GMP

#include <math.h>

int main() {
  double base = 2;
  double exponent = 4;

  double result = pow(base, exponent);

  return 0;
}
+2
source

All Articles