【问题标题】:Raise to the power of a number (iterative method)乘以数的幂(迭代法)
【发布时间】:2017-04-30 11:46:54
【问题描述】:

我们编写了 power 的递归版本,它接受一个双精度 x 和一个整数 n 并返回 x^n。现在编写一个迭代方法来执行相同的计算。

如何计算数字的幂?我的代码一遍又一遍地打印结果,我不知道为什么。

public class seventhree {
    public static void main(String[] args){
        Scanner in= new Scanner(System.in);
        int x;
        int n;

        System.out.print("Type in a base:  ");
        x= in.nextInt();

        System.out.print("Type in an exponent: ");
        n= in.nextInt();

        while(n>=2){
            System.out.println((x)*(n));
            System.out.println();
        }
    }
}

【问题讨论】:

  • 由于 n 在 while 循环内没有变化,因此条件始终为真。
  • 你所拥有的是一个无限循环。只要n 至少为2,它就会继续运行,并且循环中的任何内容都不会改变n,因此它永远不会结束。另外,您所写的与计算功率无关。另外,fix your indentation。没有理由让代码看起来像那样。

标签: java


【解决方案1】:

因为n 没有改变,你必须减少 n 直到它

int rs = 1;
while (n > 0) {
    rs *= x;
    n--;
}
System.out.println(rs);

结果示例

Inputs       Outputs
x = 6        36
n = 2

x = 2        8
n = 3

【讨论】:

    【解决方案2】:

    您可以使用Bit Manipulation 技术来实现此功能,该技术将为您提供O(log(exponent)) 复杂度的输出。

    想法是将指数拆分为power 的2 的整数之和。然后我们可以使用base^1,base^2,base^4....的结果的数字最后我们可以将所有在binary representation中设置的位相乘,这将给我们最终答案。

    long ans=1;
    
    while(n > 0)
    {
        if((n&1)!=0)  //Checking if the bit is set or not
            ans*=x;
    
        x*=x;         //squaring the base
        n=n>>1;       //shifting exponent to check next bit
    }
    System.out.println(ans);
    

    在您的代码中,您不会递减n,因此它最终会陷入无限循环。因此,您可以对代码进行一些更改。

    long ans=1;
    while(n>=1)
    {
        ans*=x;
        n--;
    }
    System.out.println(ans);
    

    【讨论】:

      猜你喜欢
      • 2020-12-17
      • 2014-11-05
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多