[英]Multiplication in Java using recursion
I am new to programming and I am writing a simple code in Java that is using recursion.我是编程新手,我正在使用递归在 Java 中编写一个简单的代码。 I want to show the product of two numbers (from start to End).
我想显示两个数字的乘积(从开始到结束)。 The return of the method is the multiplication of the numbers from start to end.
该方法的返回是从开始到结束的数字相乘。 (For Example: If the numbers are 1 and 3 then I want the method to return 6. I managed to do the recursion but I am not sure if the code is effective at all. Here is my code so far. Thanks
(例如:如果数字是 1 和 3,那么我希望该方法返回 6。我设法进行了递归,但我不确定代码是否有效。到目前为止,这是我的代码。谢谢
public class ÜbungsblattSieben {
public static void main(String[] args) {
System.out.println(multiplyFromStartToEnd(1, 3));
}
public static int multiplyFromStartToEnd(int start, int end) {
if (start == end) {
return end;
} else {
return start * multiplyFromStartToEnd(++start, end);
}
}
}
Your code is as effective as a recursive multiplication can be.您的代码与递归乘法一样有效。 Well done.
做得好。
That said, here are a few notes:也就是说,这里有一些注意事项:
You may write start + 1
instead of ++start
.你可以写
start + 1
而不是++start
。 Generally easier to read and understand.通常更容易阅读和理解。 Also you do not have to change the
start
variable itself, you just want to pass a bigger number to the method call, thats all.此外,您不必更改
start
变量本身,您只需要将更大的数字传递给方法调用,仅此而已。
You may also want to properly indent your code (just hit the auto-format key in your IDE).您可能还想正确缩进您的代码(只需在 IDE 中点击自动格式化键)。
I would also suggest to rename your method to multiplyFromTo
, but thats a very subjective note.我还建议将您的方法重命名为
multiplyFromTo
,但这是一个非常主观的说明。
All in all, your code would then look like:总而言之,您的代码将如下所示:
public class ÜbungsblattSieben {
public static void main (String[] args) {
System.out.println(multiplyFromStartToEnd(1, 3));
}
public static int multiplyFromTo(int start, int end) {
if (start == end) {
return end;
} else {
return start * multiplyFromStartToEnd(start + 1, end);
}
}
}
For reference, here is how an iterative version could look like:作为参考,以下是迭代版本的外观:
int result = 1;
for (int i = start; i <= end; i++) {
result *= i;
}
System.out.println(result);
Obviously, this is a lot faster than recursion.显然,这比递归要快得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.