快速找到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 int
或uint64_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
位位置设置1
:1 << x
。
在这种情况下,x
应该小于整数类型的宽度,而x
应该是正的。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 枚举环境变量的惯用C++14/C++17方法
- 初始化具有非默认构造函数的std::数组项的更好方法