快速找到2^x的方法

Method to find 2^x quickly

本文关键字:方法      更新时间:2023-10-16

如何在C中快速找到2^x。如果你们有任何想法,请帮忙。

是int还是float?对于int,请使用左移。对于float,pow()函数

向左移位,每移位一位,数字就会乘以2,就像向左移位小数会乘以10一样。

使用<<运算符,如下所示:

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;

依此类推,直到到达CCD_ 2。如果您使用的是有符号的32位整数,那么1 << 31会因为2的补码而给您-2147483648。如果您想要更高,请使用long long unsigned intuint64_t(64位整数)。或者,如果您的平台支持uint128_t

如果你想更高,你需要滚动你自己的"大整数"代码。请注意,有些平台和编译器带有128位整数类型,但运行时性能各不相同:它们可能需要一个可以执行128位操作的处理器,也可能将其分解为两个64位操作。

回想一下,在二进制系统中,N位置的一位代表2^N。因此,正int的公式是

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

输出:

7.0 ^ 3 = 343.000000
4.73 ^ 12 = 125410439.217423
32.01 ^ 1.54 = 208.036691
 #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 */

x位位置设置11 << x

在这种情况下,x应该小于整数类型的宽度,而x应该是正的。