我正在使用一本教科书、YouTube和在线找到的练习题来自学AP计算机科学A。其中一份练习是关于递归的,要求我将下面的代码转换为递归形式,然而,无论是教科书还是YouTube都没有解释如何从迭代转换为递归。
public static int iterative(int x){
int count=0;
int factor=2;
while(factor<x){
if(x%factor==0)
count++;
factor++;
}
return count;
}
下面的代码是我的尝试,但我一直收到StackOverFlowError错误。
public static int recursion(int x){
int count=0;
int factor=2;
if(factor>x)
return count;
else if(x%factor==0){
factor++;
count++;
}
return count + (recursion(x));
}
请问如何将迭代转换为递归?谢谢。