【问题标题】:Java recursive method for summing the powers of 2, from 0 to NJava递归方法求和2的幂,从0到N
【发布时间】:2013-01-31 03:41:28
【问题描述】:

所以我想学习递归(我知道在这种情况下递归是不必要的)

这个方法我已经写好了,行得通

public static int method(int number) {
    if(number == 0) {
        return 1;
    }
    else {
        return (int)Math.pow(2,number) + method(number-1);
    }
}

这非常适合将 2 的幂从 0 加到数字,但我想知道是否有办法用另一个递归方法调用替换 Math.pow()

【问题讨论】:

  • Burn Math.pow() 只需要一次执行。为什么要在这里递归?
  • @KanagaveluSugumar - “迭代是人类;递归是神圣的。”
  • 为什么不返回没有循环或递归的结果? return (int)Math.pow(2,number+1) -1;
  • @MrSmith42 仅适用于对 2 的幂求和,如果将其更改为 3,它将不再起作用。这也是关于学习递归而不是求和 2 的最简单方法
  • 当更改为 3 时,您可以将公式更改为 return (int)(Math.pow(3,number+1) -1) / 2。对于任何数字,这都可以概括(几乎不用考虑)。

标签: java methods recursion


【解决方案1】:

您可以将其用作递归幂函数:

public static int powerOf2(int number) {
    if (number == 0) {
        return 1;
    } else {
        return 2 * powerOf2(number - 1);
    }
}

或者,作为一个单行正文:

return number > 0 ? 2 * powerOf2(number - 1) : 1;

【讨论】:

  • 有没有办法将两者结合成一个方法?
  • @KailuaBum - 递归关系是 f(n) = 2^n + f(n-1)。您需要将其转换为双递归关系以摆脱 2^n 术语。没有什么明显的想法。
【解决方案2】:

您应该定义另一种递归方法来递归计算 Math.pow(2,n)。 但是我建议做 2 的位移运算来快速计算 Math.pow(2,n) 。例如移位 2

【讨论】:

  • 应该是2 << (n-1) 或(更好)1 << n,因为 2^1 = 2,而不是 4。
  • 确实应该是1 << n。使用2 << (n-1) 不适用于n==0
【解决方案3】:

如果您想学习递归,请举一个著名的 Fabonacci 系列示例。

public int getNthFibonacci( int n )
    {
        if ( n == 1 || n == 2 ) 
            return 1;

      else
        return getNthFibonacci( n-1 ) + getNthFibonacci( n-2 );
    }

public static void main(String[] args){

        Recursion myRecursor = new Recursion();
        System.out.println( myRecursor.getNthFibonacci(5) );

    }

但在您的情况下,它也可以通过 for 循环轻松完成。

public static void main(String[] args) {

       int sum = 0;     
        for (int number = 20; number>0; number--)
        {
            sum += Math.pow(2,number);
        }

        System.out.println(sum);

}

【讨论】:

    【解决方案4】:

    更通用的解决方案:

    public static int pow (int base, int ex) {
        if (ex == 0) {
            return 1;
        } else if (ex == 1) {
            return base;
        } else if(ex > 1) {
            return (pow(base, ex - 1) * base);
        } else {
            return pow(base, ex + 1) / base;
        }
    }
    

    这处理所有可能的情况,其中传递的值是整数..

    【讨论】:

    • 最好将ex 声明为int。否则,如果它恰好不是整数值,则该方法将递归,直到堆栈溢出。
    • 我认为你是对的。我将编辑我的答案,使其仅适用于整数。
    【解决方案5】:

    您的问题可能远非严格的问题是计算几何级数的总和,是一个连续项之间比率恒定的级数

    您的第一个元素等于 1(作为 2 pow 0)并且您的比率等于 2。因此,您可以将它与常见的、众所周知的等式一起使用,而不是使用任何递归:

    public long computGemetricSeries(int n) {
      long firstElem = 1;
      long ratio = 2;
    
      return (firstElem * (1 - Math.pow(ration,n)) / (1 - ratio));
    }
    

    或者对于一般术语(不仅是幂 o 2):

    public long computGeometricSeries(int n, double ration, double firstElem) {
       return (firstElem * (1 - Math.pow(ration,n)) / (1 - ration));
    }
    

    如果你真的想在这里递归,你可以将Math.pow(ration,n)更改为其他答案提出的一些递归函数。

    我认为这对解决您的问题没有多大帮助,但会是一个很好的了解答案。

    【讨论】:

      【解决方案6】:
      public class ComputePowerUsingRecursion {
      
          public static void main(String[] args) {    
              System.out.println(computePower(2,5));  // Passing 2 for power of 2
              System.out.println(computePower(2,-5)); // Number would be +ve or -ve
          }
      
          /**
           * <p>Compute power</p>
           * 
           *  p(x,n)  =  1              if(x=0)
           *          =  x*p(x,n-1)     if(n>0)
           *          =  (1/x)*p(x,n+1) if(n<0)  
           * @param x
           * @param n
           * @return
           */
          public static double computePower(double x, double n){
              //base case
              if(n==0){
                  return 1;
              }else if(n>0){   //recursive condition for postive power
                  return x*computePower(x, n-1);
              }else if(n<0){  //recursive condition for negative power
                  return (1/x)*computePower(x, n+1);
              }else{ 
                  return -1;
              }
          }
      }
      

      【讨论】:

        【解决方案7】:
        public static void main (String[] args){
            Integer output = 0;
            output = sumOfThePower(end, 1, 1); //input the number you like at 'end' to get the sum
            System.out.println(output);
        }
        public static Integer sumOfThePower (int end, int start, int mul){
        if (start <= end){
            mul =2 * mul;
            return mul + sumOfThePower(end, start + 1, mul);
        }
        else{
            return 1;
        }
        }
        

        【讨论】:

        • 这确实回答了这个问题,但最好提供关于这段代码为什么以及如何回答 OP 问题的说明
        猜你喜欢
        • 2014-03-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-02
        • 2013-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-20
        相关资源
        最近更新 更多