2 ^ x quick search method

How to find 2 ^ x quickly in C. If you have any ideas, please help.

+4
source share
6 answers

Bitshift to the left, this multiplies the numbers by 2 for each space shift, in the same way that moving the decimal numbers to the left multiplies them by 10.

Use the << operator, for example:

 int twoPowZero = 1; // any number^0 is 1 int twoPowOne = 1 << 1; // this sets the '2' bit to '1' int twoPowTwo = 1 << 2; int twoPowFive = 1 << 5; int twoPowTen = 1 << 10; 

etc. until you reach 1 << 30 . If you use a signed 32-bit integer, then 1 << 31 will give you -2147483648 due to two additions. If you want to go higher than using long long unsigned int or uint64_t (64-bit integer). Or, if your platform supports it: uint128_t .

If you want to go even higher, you will need to collapse your own Big Whole code. Note that some platforms and compilers have a 128-bit integer type, but execution performance varies: they may require a processor that can perform 128-bit operations, or they can split it into two 64-bit operations.

+11
source

Is it int or float? For int use left shift. For the float function, pow ()

+13
source

Recall that in the binary system, the bit at position N represents 2^N Therefore, the formula for a positive int is

 1 << x 
+4
source
 #include <stdio.h> #include <math.h> int main () { printf ("7.0 ^ 3 = %lf\n", pow (7.0,3)); printf ("4.73 ^ 12 = %lf\n", pow (4.73,12)); printf ("32.01 ^ 1.54 = %lf\n", pow (32.01,1.54)); return 0; } 

output:

 7.0 ^ 3 = 343.000000 4.73 ^ 12 = 125410439.217423 32.01 ^ 1.54 = 208.036691 
+3
source
  #include <math.h> float powf(float x, float y); /* C99 */ double pow(double x, double y); long double powl(long double x, long double y); /* C99 */ 
+3
source

Set a 1 to the xth bit position: 1 << x .

In this case, x must be less than the width of the integer type, and x must be positive.

+3
source

Source: https://habr.com/ru/post/1432853/


All Articles