将迭代转换为递归 [英] Converting Iteration to Recursion

查看:80
本文介绍了将迭代转换为递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在教科书、YouTube 和网上找到的工作表的帮助下自学 AP 计算机科学 A.其中一份工作表是关于递归的,并要求我将下面的代码转换为递归,但是教科书或 YouTube 都无法解释如何从迭代转换为递归.

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;
    }

下面的代码是我的尝试,但我不断收到 StackOverFlowError.

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.

推荐答案

正如 JackVanier 针对这个特定问题已经解释的那样,您必须将 factor 作为方法参数传递.但是公共方法签名应该保持不变,因此您必须编写两个新方法:一个是可公开访问的,具有预期的签名,另一个是真正递归并由另一个方法调用.

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);
}

还值得一提的是,您需要一个中断递归的停止条件.这就是您已经正确的事情,并且 factor >= x 条件最终在任何情况下都类似于 true.

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.

这篇关于将迭代转换为递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆