gpt4 book ai didi

algorithm - 求幂程序

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:21:19 24 4
gpt4 key购买 nike

我正在尝试快速求幂。但是结果似乎并没有产生正确的结果。任何帮助,将不胜感激。编辑:设法解决它感谢所有帮助。

        if (content[i] == '1')
s1 = (int)(po1 * (Math.pow(po1, 2)));
else
s1 = po1 * po1;
final_result *= temp;

最佳答案

看看这个 Exponation by squaring

每次遇到指数中的 1 位时,您可能希望向右移位并对基数求平方

int pow(int base, int e)
{
int retVal = 1;
while (e)
{
if (e % 2 == 1)//i.e. last bit of exponent is 1
retVal *= base;
e >>= 1; //bitshift exponent to the right.
base *= base; // square base since we shifted 1 bit in our exponent
}

return retVal ;
}

考虑它的一个好方法是你的指数被分解:比如说,6^7(位指数是 1, 1, 1)= 6^1 * 6^2 * 6^4 = 6 * 36 * 36^2 = 6 * 36 * 1296。你的基地总是在摆平自己。

关于algorithm - 求幂程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26410655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com