递归方法 - Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19067013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:50:40  来源:igfitidea点击:

Recursive method - Java

javamethodsrecursion

提问by MOTIVECODEX

Addition information:

补充资料:

Chip doesn't support multiplication, only addition. I should work around this problem by creating a recursive method, mult(), that performs multiplication of x and y by adding x to itself y times. Its arguments are x and y and its return value is the product of x and y. I should then write the method and a main() to call it.

芯片不支持乘法,只支持加法。我应该通过创建一个递归方法 mult() 来解决这个问题,该方法通过将 x 加到自身 y 次来执行 x 和 y 的乘法。它的参数是 x 和 y,它的返回值是 x 和 y 的乘积。然后我应该编写方法和一个 main() 来调用它。

It's pure logical thinking, but I get lost every time I try to think what to do.

这是纯粹的逻辑思维,但每次我试图思考该做什么时,我都会迷失方向。

I am stuck at the math part.. What I have, that doesn't work and I know the math is wrong, but I am not good at this:

我被困在数学部分..我所拥有的,那不起作用,我知道数学是错误的,但我不擅长这个:

public static void mult(int x, int y) {
    x = 0;
    y = 0;
    if (y > 0) {
        for (int i = 0; i < y; i++) {
            x = x * (x * y);
            return mult(x, y);
        }
    }
}

采纳答案by MOTIVECODEX

public static int mult(int x, int y) {
        if (y == 0) {
            return 0;
        }
        if (y > 0) {
            return x + mult(x, y - 1);
        } else {
            return -x + mult(x, y + 1);
        }
    }

this was the solution by the way

顺便说一下,这是解决方案

回答by duffymo

When I hear "recursion", I expect to see two things:

当我听到“递归”时,我希望看到两件事:

  1. A function calling itself with modified argumentseach time.
  2. A stopping conditionright at the top that tells the function when to stop, avoiding an infinite stack.
  1. 每次使用修改后的参数调用自身的函数。
  2. 一个停止条件在顶部,它告诉函数权何时停止,避免了无限的堆栈。

So where are yours? Start with writing those down in words before you write code.

那么你的呢?在编写代码之前,先用文字写下来。

回答by subsub

... by adding x to itself y times.

...通过将 x 添加到自身 y 次。

You could actually do that, instead of multiplying. Oh, and maybe if you don't set both x and y to zero, you would have something to add ;-)

你实际上可以这样做,而不是乘法。哦,也许如果您不将 x 和 y 都设置为零,您将需要添加一些内容 ;-)

One last thing: If you want a recursive solution, you don't need the for-loop.

最后一件事:如果您想要递归解决方案,则不需要 for 循环。

回答by óscar López

All you need to remember is that a multiplication is a repeated addition (assumingthat both operands are >= 0), so we have:

你需要记住的是,乘法是一个重复的加法(假设两个操作数都是>= 0),所以我们有:

  • The base case is when yis zero
  • If yis not zero, then add xone more time, and subtract 1from y
  • 基本情况是什么时候y为零
  • 如果y不为零,然后添加x一个更多的时间,并减去1y

Notice that as long as yis positive, it'll eventually have a value of zero. So basically we keep adding xa total number of ytimes; this is what I mean:

请注意,只要y是正数,它最终的值就会为零。所以基本上我们一直在增加x总数y;这就是我的意思:

public static int mult(int x, int y) {
    if (y == 0)
        return 0;
    return x + mult(x, y-1);
}

The same code can be written in a tail-recursivestyle, too - meaning: there's nothing to do after the recursive call returns, and this is important for certain languages that support a so-called tail-call optimization:

相同的代码也可以用尾递归风格编写- 意思是:递归调用返回后无事可做,这对于支持所谓的尾调用优化的某些语言很重要:

public static int mult(int x, int y, int accumulator) {
    if (y == 0)
        return accumulator;
    return mult(x, y-1, x + accumulator);
}

The above will get called as follows, noticing that the last parameter is always initialized in zero:

上面将按如下方式调用,注意最后一个参数始终初始化为零:

mult(10, 5, 0)
=> 50

回答by Display Name

Java has no TCO by design, so using recursion for linear (not tree-like) processes is very bad idea. Especially for such task, which will most likely become a bottleneck in your program. Use loop instead.

Java 在设计上没有 TCO,因此对线性(不是树状)进程使用递归是非常糟糕的主意。特别是对于这样的任务,它很可能会成为您程序中的瓶颈。改用循环。

Oh, it must be recursive anyway? Looks like a homework task. Do it yourself then.

哦,无论如何它必须是递归的?看起来像是家庭作业。那就自己做吧。

回答by user2336315

One possibility is to use an accumulator which will store the current value of the multiplication. I replace missing statements by ??? :

一种可能性是使用一个累加器来存储乘法的当前值。我用 ??? 替换丢失的语句 :

public static void main(String []args){
        System.out.println(mult(2,5));
 }
    public static int mult(int x, int y) {
      if(???) return ???;
      else return multAcc(???,???,???);
    }

    private static int multAcc(int x, int y, int acc){
        if(???) return ???;
        else return multAcc(???, ???, ???);
    }