基本Java递归方法
我在java中的这个基本递归问题上遇到了很多麻烦;任何指点都很好 “编写一个静态递归方法,打印出 几何顺序:2,6,18,54。“基本Java递归方法,java,recursion,Java,Recursion,我在java中的这个基本递归问题上遇到了很多麻烦;任何指点都很好 “编写一个静态递归方法,打印出 几何顺序:2,6,18,54。“ 从我所能收集到的信息来看,在代码中的某个地方,我应该递归地将某个值乘以3,但我正在努力找出如何做到这一点。我知道我需要一份终止声明,但什么时候会发生?我需要助手方法吗?这是最简单的递归示例 您需要一个方法声明 您需要检查是否已到达终点 否则,您需要再次调用该方法,并使用一个操作来区分一个术语和下一个术语。是的,您需要一个终止条件-基本上是在您采取了所需的步骤之后。因
从我所能收集到的信息来看,在代码中的某个地方,我应该递归地将某个值乘以3,但我正在努力找出如何做到这一点。我知道我需要一份终止声明,但什么时候会发生?我需要助手方法吗?这是最简单的递归示例 您需要一个方法声明 您需要检查是否已到达终点
否则,您需要再次调用该方法,并使用一个操作来区分一个术语和下一个术语。是的,您需要一个终止条件-基本上是在您采取了所需的步骤之后。因此,考虑如何从一个调用转换到另一个调用:
- 到目前为止,您将如何传播结果
- 你还需要什么额外的状态来记录你还需要采取多少步骤
- 您将从该方法返回什么
- 这里有一个C#示例(我知道你在使用Java,但它非常相似)
publicstaticvoidrecursive(int计数器、int迭代、int值、int乘数)
{
if(计数器<迭代次数)
{
控制台写入线(值);
计数器++;
递归(计数器,迭代,(值*乘数),乘数);
}
}
因此,当您运行函数时,您可以输入参数
- 第一次调用时,“计数器”将始终为0
- “迭代次数”是n的值
- 在您的案例2中,“值”是您的起始值
- “乘数”是指在您的案例3中,每个迭代要乘以多少
public class Inception {
public void dream() {
boolean enoughDreaming = false;
//Some code logic below to check if it's high time to stop dreaming recursively
...
...
if(!enoughDreaming) {
dream(); //Dream inside a Dream
}
}
}
以及您的问题的解决方案:
public class GeometricSequence {
public static void main(String[] args) {
//Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.
System.out.println(findNthNumber(5, 1, 2));
}
public static int findNthNumber(int n, int count, int res) {
return ((count == n)) ? res : findNthNumber(n, count+1, res *3);
}
}
编辑:
上面的类使用“int”,这只适用于小数字(因为整数溢出问题)。以下类别适用于所有类型/编号:
public class GeometricSequence {
public static void main(String[] args) {
//Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.
System.out.println(findNthNumber(2000, 1, new BigInteger("2")));
}
public static BigInteger findNthNumber(int n, int count, BigInteger res) {
return ((count == n)) ? res : findNthNumber(n, count+1, res.multiply(new BigInteger("3")));
}
}
递归解决方案:Seq(1)是序列的第一个元素。。。。序号(第n个)
非递归解决方案:
public static int Non_RecSeq(int n){
int res = 2;
for(int i = 1; i < n; i ++)
res *= 3;
return res;
}
public static void main(String args[]) throws Exception {
int x = Non_RecSeq(3); //x-> 18
}
public static int Non_RecSeq(int n){
int res=2;
对于(int i=1;i18
}
public static void main(String args[]) throws Exception {
int x = Seq(3); //x-> 18
}
public static int Seq(int n){
return SeqRec(n);
}
private static int SeqRec(int n){
if(n == 1)
return 2;
else return SeqRec(n - 1) * 3;
}
public static int Non_RecSeq(int n){
int res = 2;
for(int i = 1; i < n; i ++)
res *= 3;
return res;
}
public static void main(String args[]) throws Exception {
int x = Non_RecSeq(3); //x-> 18
}