gpt4 book ai didi

java - 使用递归来乘以没有局部变量的数字序列

转载 作者:行者123 更新时间:2023-11-29 04:32:15 25 4
gpt4 key购买 nike

这是一道让我和我的同学都难过的过去考试的题目:

Use recursion to multiply together every number in a series without using local variables. Assume:

  • the parameters are positive
  • the first parameter is less than the second parameter
  • the result is less than 231

例如,rangeProduct(1, 5) 应该返回 120,因为 1x2x3x4x5 是 120

使用这个方法签名:

public static int rangeProduct(int valueOne, int valueTwo) {
return ?;
}

如果有人知道如何做到这一点,那只是为了让我的学习受益,如果您正在寻找一些练习,或者只是对一个饥肠辘辘、知识一般的计算机科学专业的学生表示同情,那就试试吧!

最佳答案

试试这个:

public static int rangeProduct(int valueOne, int valueTwo) {
if(valueOne>=valueTwo)
return valueOne;
return rangeProduct(valueOne, valueTwo-1) * valueTwo;
}

按照您指定的确切顺序执行计算:

1x2=2, 2x3=6, 6x4=24, 24x5=120

关于java - 使用递归来乘以没有局部变量的数字序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43373099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com