问题
I am teaching myself AP Computer Science A with the help of a textbook, YouTube, and worksheets found online. One of the worksheets was on recursion and asked me to convert the code below to recursion, however, neither the textbook or YouTube could explain how to convert from iteration to recursion.
public static int iterative(int x){
int count=0;
int factor=2;
while(factor<x){
if(x%factor==0)
count++;
factor++;
}
return count;
}
The code below is my attempt, but I keep getting a 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));
}
Could someone please explain how to convert from iteration to recursion? Thank you.
回答1:
As already explained by JackVanier for this particular problem you will have to pass in factor as a method argument. But the public method signature should stay the same so you have to write two new methods: One that is publicly accessible, has the intended signature and one that is truly recursive and is called by the other method.
public static int recursive(int x) {
return recursive(x, 2);
}
private static int recursive(int x, int factor) {
if (factor >= x)
return 0;
if (x % factor == 0)
return 1 + recursive(x, factor + 1);
return recursive(x, factor + 1);
}
It's also worth mentioning that you need a stop condition that breaks the recursion. That's the thing you have already got correct and it is the factor >= x
condition that eventually resembles true
in any case.
回答2:
You will need to pass in factor as a variable to the method. So the method signature will look like public static int recursion(int x, int factor)
. Because the way you have it factor is always 2 because each time you call the method the factor
variable gets reset to 2.
回答3:
public static int recursion(int x, int factor)
{
int count=0;
if(factor>x)
return count;
else if(x%factor==0)
{
++factor;
++count;
}
return count + (recursion(x, factor));
}
The only difference is changing the header, removing int factor=2, and the return statement at the bottom. When using recursion instead of iteration, you will have to pass more variables as a general rule. Otherwise the problem you were having with StackOverFlowError sprung from the fact that you did pass the updated factor value. This caused the default case to never be true, and essentially created an infinite loops only stopped by the fact that calling methods is resource heavy and will throw that error if the default case is not reached. The default case being: return count; when the if statement (factor>x) becomes true.
来源:https://stackoverflow.com/questions/42495744/converting-iteration-to-recursion