计算能力的迭代解决方案

问题描述

我正在开发一种有效的迭代代码来计算m n 。经过一番思考和谷歌搜索,我找到了这段代码;

public static int power(int n,int m)
// Efficiently calculates m to the power of n iteratively
{
int pow=m,acc=1,count=n;
while(count!=0)
{
 if(count%2==1)
    acc=acc*pow;
 pow=pow*pow;
 count=count/2;
}
return acc;
}

除了我为什么每次都将pow的值都平方时,这个逻辑对我来说很有意义。我熟悉类似的递归方法,但是对我来说,这种平方不是很直观。我能帮她一下吗?带有解释的示例将非常有帮助。

解决方法

每次迭代都会对累加器进行平方,因为count(这是逆累积功率)在每次迭代中都会被减半

如果计数为奇数,则将累加器乘以数字。该算法依靠整数算法,该算法舍弃除法的小数部分,当计数为奇数时有效地再减1。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...