Java recursive method for summing the powers of 2, from 0 to N

£可爱£侵袭症+ 提交于 2019-12-11 10:59:02

问题


so im trying to learn recursion (i know in this case recursion is not necessary)

i have already written this method, which works

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

this works perfectly for summing the powers of 2 from 0 to number, but i was wondering if there was a way to replace the Math.pow() with another recursive method call


回答1:


You can use this as a recursive power function:

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

Or, as a one-line body:

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



回答2:


You should define another recursive method to calculate Math.pow(2,n) recursively probably. However I would suggest to do bit shift operation of 2 to calculate Math.pow(2,n) quickly. For example shifting 2 << (n-1) will do hob here.




回答3:


If you want to learn Recursion take a well known example of Fabonacci series.

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) );

    }

But in your case it can be done by for loop also easily.

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:


A more general solution:

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;
    }
}

This handle all possible cases where the passed values are integers..




回答5:


Maybe a little far from strict question your problem is to calculate sum of geometric series which is a series with a constant ratio between successive terms.

Your first element is equal to 1 (as 2 pow 0) and your ratio is equal to 2. So instead of using any recursion you can use it with common, well-know, equatation:

public long computGemetricSeries(int n) {
  long firstElem = 1;
  long ratio = 2;

  return (firstElem * (1 - Math.pow(ration,n)) / (1 - ratio));
}

Or for general term (not only power o 2):

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

If you realy want recursion here you can change Math.pow(ration,n) to some recursion function proposed by other answers.

I think it won't help much as resolution to your question but will be a nice good-to-know answer.




回答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;
}
}


来源:https://stackoverflow.com/questions/14618055/java-recursive-method-for-summing-the-powers-of-2-from-0-to-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!