递归方法(在不使用Math.pow的情况下,将2的幂的总和返回到2的x次幂作为整数)

时间:2016-09-14 05:28:42

标签: java recursion

我正在创建一个递归代码,它可以执行5个方法等等。我的递归方法存在问题,它将返回并在main()中打印2的幂的总和,直到2的X次方.X是命令行参数的整数。

我能够进行math.pow过程但是如何在不使用Math.Pow的情况下进行此操作?

我的代码(问题是powerCount方法)。

public class TestRun {
/*
* The "main" Method Starts The Program.
* @param args (commandline arguments) are printed to the screen
*/

   public static void main (String[]args) {

   //initialize variables
      int num = 0;
      String result = "";
      /***********************************
    * @ Try-Catch Checks for valid input
      * **********************************/
      try{
         if(args.length == 0)
         {
            System.out.println("ERROR:NO INPUT FOUND.");
         }//end of if
         else
         {
         //convert 1st commandline argument from string to integer    
            num = Integer.parseInt(args[0]);
         //method call to 1st method   
            result = rowOfAsterisks(num);
         //display output of 1st method to screen    
            System.out.println(result);
         //method call to 2nd method   
            result = forwardCount(num);
         //display output of 2nd method to screen    
            System.out.println(result);
         //method call to 3rd method   
            result = reverseCount(0, num);
         //display output of 3rd method to screen    
            System.out.println(result);
         //method call to 4th method   
            Integer result2 = addCount(0,num);
         //display output of 4th method to screen    
            System.out.println(result2);
         //method call to 5th method    
            result2 = powerCount(1,(int)Math.pow(2,num));
         //display output of 5th method to screen    
            System.out.println(result2);
         }//end of else
      }//end of try
      catch(NumberFormatException e)
      {
         System.out.print("ERROR: Please input an integer.");
      }
   }//end of main

    /**************************
    * Writes x asterisk
    * @param num is input of the user and will determine the number of asterisks
    * @return x asterisk
    ***************************/
   public static String rowOfAsterisks(int num)
   {
      //base case
      if(num ==1){
         return "*";
      }
      //recursive case
      else{
         return "*" + rowOfAsterisks(num-1); 
      }//end of else
   }//end of method1

    /*****************************
    * Counts from number to zero.
    * @param num is the input of the user or the argument
    * @return string num
    *****************************/
   public static String forwardCount(int num)
   {
      //base case
      if(num==0){
         return num + ", ";
      }
      //recursive case
      else{
         return  num + ", " + forwardCount(num-1);
      }//end of else
   }//end of method 2

    /***************************************************
    * Counts from zero to number.
    * @param initialNum is the input/initial integer
    * @param finalNum is the final integer
    * @return initialNum and finalNum as a String.
    ****************************************************/
   public static String reverseCount(int initialNum, int finalNum)
   {
      //base case
      if(initialNum == finalNum){
         return initialNum + ", ";
      }
      //recursive case
      else{
         return initialNum + ", " + reverseCount(initialNum +1, finalNum);
      }//end of else
   }//end of method 3

    /*****************************************************
    * Adds the number from 0 to number and returns the sum
    * @param initialNum is the input/initial integer
    * @param finalNum is the final integer
    * @return initialNum and finalNum as a String(again)
    ****************************************************/
   public static int addCount(int initialNum, int finalNum)
   {
      //base case
      if(initialNum == finalNum){
         return initialNum;
      }
      //recursive case
      else{
         return initialNum + addCount(initialNum + 1, finalNum);
      }//end of else
   }//end of method4

    /**********************************************************
    * Multiply number by the power of 2 and returns the product
    * @param initialNum is the input/initial integer
    * @param finalNum is the final integer
    * @return initialNum and finalNum as an Integer
    ***********************************************************/
   public static int powerCount(int initialNum, int finalNum)
   {
      //base case
      if(initialNum == finalNum){
         return initialNum;
      }
      //recursive case
      else{
         return initialNum + powerCount(initialNum *2, finalNum);
      }//end of else
   }//end of method5
}//end of class

这是powerCount方法:

public static int powerCount(int initialNum, int finalNum)
   {
      //base case
      if(initialNum == finalNum){
         return initialNum;
      }
      //recursive case
      else{
         return initialNum + powerCount(initialNum *2, finalNum);
      }//end of else
   }//end of method5
}//end of class

这里也是我的主要方法,它调用/返回并打印它

// method call to 5th method    
result2 = powerCount(1,(int)Math.pow(2,num));
// display output of 5th method to screen    
System.out.println(result2);

2 个答案:

答案 0 :(得分:1)

你最大的问题是代码太多,所以我不会尝试调试它。

递归impl就像:

一样简单
int pow(int x, int p) {
    return p == 0 ? 1 : x * pow(x, p - 1);
}

如果您想要打印东西,请不要使用此方法。我会在这个代码之外的一个主循环中执行它,将p从1迭代到n(忘记"效率" - 这将在几微秒内执行)。

答案 1 :(得分:0)

可用的功能应该是:

/**
 * Calculates n<sup>exp</sup>.
 * @param n the base number.
 * @param exp the exponent.
 * @return the power of n to the exp.
 */
public static int power(int n, int exp) {
    // What is the easiest case (terminating the recursion?
    // - Case exp == 0 return 1
    ...
    // - Case other exp values
    // What do you know about power formulas to reduce exp?
    ... recursion with smaller exp
}

当然n^exp+1 == n * n^exp会将exp减少1.但也许你可以找到更好的减少量。

在你的情况下,块可能是非数学长名称,有时会模糊不清。使用x^n作为名称可能会更有帮助。

此外,递归以f(x, y)开头,下一步使用f(x', y')作为一种缩减。因此,对于最后一步y'是一个微不足道的案例,x'可能已经是结果。

在我们的情况下,power(x, n)将有最后一次递归调用power(x_up_n, 1)x_up_n * power(rumpelstielchen, 0)