Connor S -4 years ago 153
Java Question

# Converting Iteration to Recursion

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.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download