Java方法类似于Math.pow,具有迭代和递归的高效解决方案-作业

huangapple go评论75阅读模式
英文:

Java method like MathPow with a solution iterative and recursive in efficiency-Homework

问题

问题1:

完成以下Java方法,使得raiseToPower(x, n)将数字x提高到整数幂n(即计算值xn)。记住x-n = 1/xn,以及x0 = 1。

您应该在最少的步骤内完成(即在O(log n)时间内)。

给出一个非递归(迭代)的解决方案:

以下是我的解决方案:

public static double raiseToPower(double x, int n) {
    double res = 1;
    boolean neg = false;
    if (n < 0) {
        neg = true;
        n = -n; // 将n转换为正数
    }
    
    while (n > 0) {
        if (n % 2 == 1) {
            res *= x;
        }
        x *= x;
        n /= 2;
    }
    
    if (neg) {
        return 1 / res;
    } else {
        return res;
    }
}

但这个解决方案不够高效。

以下是我遇到的错误示例:
52.49的9次方解决需要9步,但可以在4步内完成。
89.89的75次方解决需要75步,但可以在7步内完成。
78.57的63次方解决需要63步,但可以在6步内完成。
70.17的44次方解决需要44步,但可以在6步内完成。

注意:不要使用java.lang.Math.pow方法。

问题2:

我需要编写与“问题1”完全相同的代码,但使用递归方法。

以下是我的问题:

请给出递归解决方案:

以下是我的代码:

public static double raiseToPower(double x, int n) {
    if (n == 0) {
        return 1;
    } else if (n < 0) {
        return 1 / (x * raiseToPower(x, -n - 1));
    } else {
        return x * raiseToPower(x, n - 1);
    }
}

这个代码是正确的,但不够高效。

以下是我遇到的错误示例:

53.31的44次方解决需要44步,但可以在6步内完成。
6.90的74次方解决需要74步,但可以在7步内完成。
80.76的76次方解决需要76步,但可以在7步内完成。
51.44的86次方解决需要86步,但可以在7步内完成。
76.26的50次方解决需要50步,但可以在6步内完成。
63.53的93次方解决需要93步,但可以在7步内完成。

注意:不要使用java.lang.Math.pow方法。

谢谢大家帮助解决这两个问题!

英文:

I have a problem with my homework and i need help please!

Question 1:

Complete the Java methods below so that raiseToPower(x,n) will raise the number x to an integer power n (that is, to calculate the value xn ). Remember that x-n = 1/xn,
and that x0 = 1.

You should do this in the fewest number of steps possible (that is, in O(log n) time).

Give a solution which is non-recursive (iterative):

This is my solution :

    public static double raiseToPower (double x, int n) {
double res=1;
     boolean neg=false;
     if(n&lt;0)
     {
         neg=true;

     }
     if(n&gt;0)

         for (int i=0;i&lt;n;i++) {
             res = res * x;
         }
             if(neg==true) {
                 n=n*-1;
                 for (int i=0;i&lt;n;i++) {


                     res = res * x;
                 }
                   res=1/res;
             }


             return res;
}

but this is not correct because is not efficiency

This my error for example:
52.49 to the power of 9 solved in 9 steps, but it could have been done in 4 steps
89.89 to the power of 75 solved in 75 steps, but it could have been done in 7 steps
78.57 to the power of 63 solved in 63 steps, but it could have been done in 6 steps
70.17 to the power of 44 solved in 44 steps, but it could have been done in 6 steps

Note:must not be used in method java.lang.MathPow

Question 2:

I need write code exactly like Question 1 but in recursive

This is my Question:
Give a recursive solution:

This is my code:

     public static double raiseToPower (double x, int n) {
ouble dev=0.0;
        if (n == 0) {
            return 1;
        } else {
            if (n &lt; 0) {
              double  count= raiseToPower (x, n+1);
                dev=count*x;
                return 1 / raiseToPower (x, -n);
            }
            if (n &gt; 0) {
             double  count= raiseToPower (x, n-1);
             dev=count*x;



            }

        }
        return dev;
}

This code is correct but not efficiency.

This is my error for example:

53.31 to the power of 44 solved in 44 steps, but it could have been done in 6 steps
6.90 to the power of 74 solved in 74 steps, but it could have been done in 7 steps
80.76 to the power of 76 solved in 76 steps, but it could have been done in 7 steps
51.44 to the power of 86 solved in 86 steps, but it could have been done in 7 steps
76.26 to the power of 50 solved in 50 steps, but it could have been done in 6 steps
63.53 to the power of 93 solved in 93 steps, but it could have been done in 7 steps

Note:must not be used in method java.lang.MathPow

Thank you everyone for helping and solving both problems !!!

答案1

得分: 1

你可以通过将 n 拆解为 2 的幂来计算 x 的 n 次方,时间复杂度为 O(logN),方法如下:

9 = 1+8

15 = 1+2+4+8

因此,x^9 = (x^1)*(x^8)。

为了将 n 拆解为 2 的幂,你可以使用位运算符。像这样:n&pow2 意味着你对 N 和 pow2 进行“与”操作,这意味着如果 n 的某一位为 1,而 pow2 的对应位也为 1,结果将不为零。鉴于 pow2 必须有一个单独的位为 1(它是 2 的幂),你可以基本上检查 n 的每一位。因此,你将 n 拆解为 2 的幂,然后在找到 n 确实由那个 2 的幂组成时,可以将它与 res 相乘。

因此,我们可以为第一个解决方案编写以下代码:

  public static double raiseToPower (double x, int n) {
    double res=1;
    double powx=x;
    int pow2=1;
    boolean neg=false;
    if(n&lt;0)
    {
      neg=true;
      n=n*-1;
    }
    while(n!=0) {
      if((n&amp;pow2)!=0)
      {
        res=res*powx;
        n=n-pow2;
      }
      powx=powx*powx;
      pow2=pow2*2;
    }
    if(neg==true)
      res=1/res;
    return res;
  }

这里有更多关于位运算符的文章:https://www.tutorialspoint.com/java/java_basic_operators.htm

类似地,你可以修改递归代码以将其改为 O(logN)。

以下是递归代码:

  public static double raiseToPower(double x, int n)
{
    boolean neg= false;
    double res=1;
    if(n&lt;0)
    {
      neg=true;
      n=-n;
    }
        
    if (n == 0) return 1;
    if (n % 2 == 0)
    {
      res= raiseToPower(x, n / 2);
      res=res*res;
    }
    else
    {
      res= x * raiseToPower(x, n - 1);
    }
    if(!neg)
      return res;
    return 1/res;
}

希望对你有所帮助。

英文:

You can calculate in O(logN) x^n by breaking down n in 2's powers, like so:

9 = 1+8

15= 1+2+4+8

Therefore, x^9= (x^1)*(x^8).

In order to break down n in 2's powers, you can use bitwise operators. Like this: n&pow2 would mean you do the "AND" operation between N and pow2, which means if n has a bit 1 and pow2 also has that bit 1, the result will be non-zero. Given that pow2 must have a single bit 1( it is a power of 2), you can basically check every bit of n. So you are breaking down n in the powers of 2 and you can simply keep a powx around that means x^(pow2) as you are looping through the powers of 2, then multiply it to res whenever you find that n indeed is composed of that power of 2.

So we can make this code for the first solution:

  public static double raiseToPower (double x, int n) {
    double res=1;
    double powx=x;
    int pow2=1;
    boolean neg=false;
    if(n&lt;0)
    {
      neg=true;
      n=n*-1;
    }
    while(n!=0) {
      if((n&amp;pow2)!=0)
      {
        res=res*powx;
        n=n-pow2;
      }
      powx=powx*powx;
      pow2=pow2*2;
    }
    if(neg==true)
      res=1/res;
    return res;
  }

Here's more articles about bitwise operators: https://www.tutorialspoint.com/java/java_basic_operators.htm

Similarly, you can modify the recursive code to get it in O(logN).

Here would be the recursive code:


  public static double raiseToPower(double x, int n)
{
    boolean neg= false;
    double res=1;
    if(n&lt;0)
    {
      neg=true;
      n=-n;
    }
        
    if (n == 0) return 1;
    if (n % 2 == 0)
    {
      res= raiseToPower(x, n / 2);
      res=res*res;
    }
    else
    {
      res= x * raiseToPower(x, n - 1);
    }
    if(!neg)
      return res;
    return 1/res;
}

答案2

得分: 0

public class ExponentialCalculator {

    public static void main(String[] args) {
        double x = 2;
        int n = -4;
        System.out.println(raiseToPower(x, n));
    }
    
    // 分治法
    public static double raiseToPower(double x, int n) {
        if (n == 0) {
            return 1;
        }
        double temp = raiseToPower(x, n/2) * raiseToPower(x, n/2);
        if (n % 2 == 0) {
            return n > 0 ? temp : 1/temp;	
        }
        else {
            return n > 0 ? x * temp : 1/(x * temp);
        }
    }
}

结果为 0.0625

复杂度为 O(log n)。

英文:
public class ExponentialCalculator {

	public static void main(String[] args) {
		double x = 2;
		int n = -4;
		System.out.println(raiseToPower(x, n));
	}
	
	//Divide and Conquer method
	public static double raiseToPower (double x, int n) {
		if(n==0) {
			return 1;
		}
		double temp = raiseToPower(x, n/2) * raiseToPower(x, n/2);
		if(n%2==0) {
			return n &gt; 0 ? temp: 1/temp;	
		}
		else {
			return n &gt; 0 ? x * temp: 1/(x * temp);
		}
	}
}

<br>
result 0.0625

Complexity Log(n)

huangapple
  • 本文由 发表于 2020年4月9日 16:43:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/61117215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定