首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用c中的递归方法打印两个数字之间的数字,除以数字7。

用c中的递归方法打印两个数字之间的数字,除以数字7。
EN

Stack Overflow用户
提问于 2022-01-02 22:28:47
回答 1查看 81关注 0票数 1

我想把这个非递归函数转换成递归函数。我该怎么做呢?我必须找到可被7除的两个数字之间的数字数。

代码语言:javascript
复制
void count_divisors2(int min, int max) {

    //Variable to store the counter
    int counter = 0, i;
    
    // Running a loop from A to B and check
    // if a number is divisible by M.
    for (i = min; i <= max; i++) {
        if (i % 7 == 0)
            counter++;
    }
    printf("%d", counter);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-02 23:00:53

与其打印数字,不如返回计数:

非递归版本:

代码语言:javascript
复制
int count_divisors2(int min, int max) {

    //Variable to store the counter
    int counter = 0, i;
    
    // Running a loop from A to B and check
    // if a number is divisible by M.
    for (i = min; i <= max; i++) {
        if (i % 7 == 0)
            counter++;
    }
    return counter;
}

递归版本:

代码语言:javascript
复制
int count_divisors2(int min, int max) {
    if (min > max)
        return 0;
    else
        return (min % 7 == 0) + count_divisors2(min + 1, max);
}

直接版本:

代码语言:javascript
复制
int count_divisors2(int min, int max) {
    if (min <= max) {
        if (min >= 0)
            return (max / 7) - (min / 7) + (min % 7 == 0);
        else
        if (max >= 0)
            return (max / 7) - (min / 7) + 1;
        else
            return (max / 7) - (min / 7) + (max % 7 == 0);
    } else {
        return 0;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70560232

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档