简体   繁体   English

递归方法-Java

[英]Recursive method - Java

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. 我应该通过创建一个递归方法mult()来解决此问题,该方法通过将x加到自身y次来执行x和y的乘法。 Its arguments are x and y and its return value is the product of x and y. 它的参数是x和y,其返回值是x和y的乘积。 I should then write the method and a main() to call it. 然后,我应该编写方法和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);
        }
    }
}

When I hear "recursion", I expect to see two things: 当我听到“递归”时,我希望看到两件事:

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

So where are yours? 那你呢 Start with writing those down in words before you write code. 在编写代码之前,先用文字写下来。

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(???, ???, ???);
    }

... 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循环。

All you need to remember is that a multiplication is a repeated addition ( assuming that both operands are >= 0 ), so we have: 您需要记住的是,乘法是重复的加法( 假设两个操作数均>= 0 ),因此我们有:

  • The base case is when y is zero 基本情况是y为零时
  • If y is not zero, then add x one more time, and subtract 1 from y 如果y不为零,则将x再加一次,并从y减去1

Notice that as long as y is positive, it'll eventually have a value of zero. 请注意,只要y为正,它最终将具有零值。 So basically we keep adding x a total number of y times; 因此,基本上我们一直将x总数相加y次; this is what I mean: 这就是我的意思:

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-recursive style, 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

Java has no TCO by design, so using recursion for linear (not tree-like) processes is very bad idea. Java在设计上没有TCO,因此对线性(而非树状)进程使用递归是一个非常糟糕的主意。 Especially for such task, which will most likely become a bottleneck in your program. 特别是对于此类任务,这很可能会成为您程序中的瓶颈。 Use loop instead. 使用循环代替。

Oh, it must be recursive anyway? 哦,还是必须递归吗? Looks like a homework task. 看起来像是一项家庭作业。 Do it yourself then. 那你自己做。

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 这是解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM