Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to find 2^x quickly

Tags:

c++

c

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

like image 559
RBS Avatar asked Nov 28 '22 00:11

RBS


2 Answers

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

like image 191
keltar Avatar answered Dec 11 '22 21:12

keltar


Bitshift to the left, this multiplies numbers by 2 for every place shift, in the same way that shifting decimal numbers to the left multiplies them by 10.

Use the << operator, like so:

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;

and so on until you get to 1 << 30. If you're using a signed 32-bit integer then 1 << 31 will give you -2147483648 because of two's complement. If you want to go higher than use 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'll need to roll your own "big integer" code. Note that some platforms and compilers come with a 128-bit integer type, but runtime performance varies: they may require a processor that can perform 128-bit operations, or they might break it down into two 64-bit operations.

like image 28
Dai Avatar answered Dec 11 '22 22:12

Dai