递归计算base的n次方值

发布于 2024-11-05 14:08:33 字数 338 浏览 0 评论 0原文

这是我的解决方案:

 public int powerN(int base, int n) {

    if(n == 0)
       return 1;

    else if(n % 2 == 0)
       return base * base;

    else
       return base * powerN(base, n-1); 

 }

但是,如果 n > 3 那么这个功能就不起作用了。 例如,powerN(2, 4) 产生 4,powerN(2, 5) 产生 8。 我知道存在一个更简单的解决方案,但令我困扰的是我无法弄清楚为什么它不能正常工作。

Here is what I have for my solution:

 public int powerN(int base, int n) {

    if(n == 0)
       return 1;

    else if(n % 2 == 0)
       return base * base;

    else
       return base * powerN(base, n-1); 

 }

However, if n > 3 then this function doesn't work.
For instance, powerN(2, 4) yields 4 and powerN(2, 5) yields 8.
I know that a much simpler solution exists, but it just bothers me that I can't figure out why this is not working correctly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

乖乖 2024-11-12 14:08:33
else if(n % 2 == 0)
   return base * base;

这一位是不正确的 - 它返回任何偶次幂的平方,而不仅仅是 2。看起来您正在尝试实现 平方和乘法优化。因此,如果您想要计算 powerN(base, n),您可以使用什么递归调用来利用 n 是偶数这一事实?您将为 basen 传递哪些新值?使用恒等式 b2‌n = (b2) n

else if(n % 2 == 0)
   return base * base;

This bit is incorrect — it returns the square for any even power, not just 2. It looks like you’re trying to implement the square and multiply optimization. So if you want to compute powerN(base, n), what recursive call can you make that takes advantage of the fact that n is even? What new values will you pass in for base and n? Use the identity that b2‌n = (b2)n.

菊凝晚露 2024-11-12 14:08:33

变成伪代码

让我把你的代码翻译成伪代码:

public int powerN(int base, int exponent)  {
    if the exponent is 0
        then return 1
    otherwise, if the exponent is even
        then return base * base
    otherwise
        base * powerN(base, exponent - 1)
}

第二个分支有一个逻辑错误。您的代码所说的是这样的:“只要指数是偶数,结果就应该是base * base(即base平方)”。您已经提到过,这是运行代码时得到的结果。

如何解决

您可能想要做的是将 base 提高到 exponent 的一半(base * base * base * ... for 指数/2 次),然后将该数字与其自身相乘。这样,您就可以得到基数乘以自身指数倍。

用伪代码来说:

otherwise, if the exponent is even
    then return powerN(base, exponent / 2) * powerN(base, exponent / 2)

实际上,这实际上是这样的:

otherwise, if the exponent is even
    then {
        let x = powerN(base, exponent / 2)
        return x * x
    }

完成。大多。

将其翻译回 Java 即可。

Into pseudocode

Let me translate your code into pseudocode:

public int powerN(int base, int exponent)  {
    if the exponent is 0
        then return 1
    otherwise, if the exponent is even
        then return base * base
    otherwise
        base * powerN(base, exponent - 1)
}

The second branch has a logic error. What your code is saying is this: "As long as the exponent is even, the result should be base * base (that is, base squared)". You've already mentioned that this is the result you get when you run your code.

How to solve it

What you probably want to do is to raise base to half the exponent (base * base * base * ... for exponent / 2 times), and then multiply that number by itself. That way, you get base multiplied by itself exponent times.

In pseudocode:

otherwise, if the exponent is even
    then return powerN(base, exponent / 2) * powerN(base, exponent / 2)

Realistically, this would actually be the following:

otherwise, if the exponent is even
    then {
        let x = powerN(base, exponent / 2)
        return x * x
    }

Done. Mostly.

Translate that back to Java and you'll be set.

洒一地阳光 2024-11-12 14:08:33

有问题的代码是:

else if(n % 2 == 0)
   return base * base;

这个 if 会捕获 2 的所有幂。因此 0,2,4,8 会导致错误的计算。

您应该担心的唯一极端情况n <= 0时。

这是更正后的代码:

public static int powerN(int base, int n) {
    if (n < 0) {
        throw new IllegalArgumentException("Illegal Power Argument");
    }
    if (n == 0) {
        return 1;
    } else {
        return base * powerN(base, n - 1);
    }
}

这是测试:

public static void main(String args[]) throws NullPointerException {
    for (int i = 0; i < 10; i++) {
        System.out.println(powerN(2, i));
    }
}

和输出:

run:
1
2
4
8
16
32
64
128
256
512
BUILD SUCCESSFUL (total time: 1 second)

Buggy code is:

else if(n % 2 == 0)
   return base * base;

this if will catch every power of 2. So 0,2,4,8 causes wrong calculation.

The only corner case you should worry about is when n <= 0.

Here is corrected code:

public static int powerN(int base, int n) {
    if (n < 0) {
        throw new IllegalArgumentException("Illegal Power Argument");
    }
    if (n == 0) {
        return 1;
    } else {
        return base * powerN(base, n - 1);
    }
}

Here is the test:

public static void main(String args[]) throws NullPointerException {
    for (int i = 0; i < 10; i++) {
        System.out.println(powerN(2, i));
    }
}

and output:

run:
1
2
4
8
16
32
64
128
256
512
BUILD SUCCESSFUL (total time: 1 second)
星軌x 2024-11-12 14:08:33

在偶数情况下,您需要在返回之前base = powerN(base, n/2);

In the even case you need base = powerN(base, n/2);before returning.

岛徒 2024-11-12 14:08:33

为了计算幂,您只需要考虑 x^0 的特殊情况,对于所有其他情况(n>0),您可以使用 x*powerN(x, n-1) 的递归

For computing the power you only need to consider the special case of x^0, for all others (n>0) you can use the recursion of x*powerN(x, n-1)

浮世清欢 2024-11-12 14:08:33
class Square{
    int r=1;
     int power(int n, int p) throws Exception
    {
         int s=n;
        if(n<0||p<0)
        {
        throw new Exception("n and p must be positive");
        }

    if(p==2)
    {
        return n*n*r;
    }
    else
    {
        r=r*n;
        return power(n,p-1);
    }

    }
}
class Square{
    int r=1;
     int power(int n, int p) throws Exception
    {
         int s=n;
        if(n<0||p<0)
        {
        throw new Exception("n and p must be positive");
        }

    if(p==2)
    {
        return n*n*r;
    }
    else
    {
        r=r*n;
        return power(n,p-1);
    }

    }
}
迟月 2024-11-12 14:08:33

这是 C++ 中的答案,这是一系列 a^b =

int power(int a, int b)
{
   int k = a;
   int c = b;
   if (c == 1)
    {
        return a;
    }
   else if (c == 0)
    {
        return 1;
    }
   else if (c >= 1)
   {
        c--;
        k = k*power(k,c);
   }
   cout << k << endl;
   return k;

}

int main()
{
    cout << "Enter a number " << endl;
    int n;
    cin >> n;
    cout << "Enter power " << endl;
    int c1 = 0;
    cin >> c1;
    cout << endl ;
    cout << "These are all the powers up to " << n << " to the power " << c1 << endl;
    power(n,c1);
    return 0;
}

Here is answer in C++, this is a series of a^b =

int power(int a, int b)
{
   int k = a;
   int c = b;
   if (c == 1)
    {
        return a;
    }
   else if (c == 0)
    {
        return 1;
    }
   else if (c >= 1)
   {
        c--;
        k = k*power(k,c);
   }
   cout << k << endl;
   return k;

}

int main()
{
    cout << "Enter a number " << endl;
    int n;
    cin >> n;
    cout << "Enter power " << endl;
    int c1 = 0;
    cin >> c1;
    cout << endl ;
    cout << "These are all the powers up to " << n << " to the power " << c1 << endl;
    power(n,c1);
    return 0;
}
合约呢 2024-11-12 14:08:33
public static int powerN(int base, int n ){
    if (n==0){
        return 1;
    }else
        return base*powerN(base,n-1);
}
public static int powerN(int base, int n ){
    if (n==0){
        return 1;
    }else
        return base*powerN(base,n-1);
}
思念满溢 2024-11-12 14:08:33

你的问题是代码

if (n % 2 == 0)
返回基数 * 基数;

这使得您的函数在幂 (n) 为偶数时返回底数的平方,而在幂 (n) 为奇数时返回立方。
你需要的唯一终止条件是 n==0 return 1 并且它应该递归地满足你的 n 次方底数规范

Your problem is the code

if (n % 2 == 0)
return base * base;

This makes your function return square of the base whenevr the power (n) is even and cube whenever it is odd.
The only terminating condition u need is n==0 return 1 and it should work to your specification of base to the power n recursively

維他命╮ 2024-11-12 14:08:33
public int powerN(int base, int power) {
    if (power == 1)
        return base;
    else if (power % 2 == 0) {
        int x = powerN(base, power / 2);
        return x * x;
    } else {
        int x = powerN(base, (power - 1) / 2);
        return x * x * base;
    }
}
public int powerN(int base, int power) {
    if (power == 1)
        return base;
    else if (power % 2 == 0) {
        int x = powerN(base, power / 2);
        return x * x;
    } else {
        int x = powerN(base, (power - 1) / 2);
        return x * x * base;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文