如何在递归函数中计数

how to count in recurrsive function?

本文关键字:递归函数      更新时间:2023-10-16

这是我打印除数的代码,然后打印给定数字的除数数。

现在假设我采用 2 个测试用例:5 和 8;这段代码将计数 5 作为 2,将 8 作为 6(即它添加了前一个计数)。

即使我将其声明为 int count = 0;它也会返回相同的输出。

当我在函数factors内声明int count = 0时,会出现另一个问题。

对于所有情况,代码的计数都为 0。

#include<iostream>
using namespace std;
int count;
long long factors(long n, long f=1)
{

    if(n%f==0) {
        cout << f << endl;
        count++;
    }
    if(f==n) {
        return 0;
    }
    factors(n,f+1);
    return count;
}
int main()
{
    int n;
    int t;
    cin >> t;
    while(t--)
    {
        cin >> n;
        cout << factors(n) << endl;
    }

    return 0;
}

使用全局变量通常不是一个好主意。它在递归函数中尤其糟糕,最好是可重入的。当然,您可以通过重置循环中的计数来修复函数,如下所示:

while(t--)
{
    cin>>n;
    count = 0; // Reset count before the recursive call
    cout << factors(n) << endl;
}

您还可以制作factors"包装器"来重置count,以使调用者无需在调用factors之前重置count,如下所示:

long long factors(long n) {
    count = 0;
    return factors(n, 1);
}
long long factors(long n,long f /* Remove the default */) {
    ... // the rest of your code
}
您可以通过

传递计数作为引用来实现这一点 -

#include<iostream>
using namespace std;
long long factors(long n, int& count, long f=1)
{
    if(n%f==0)
    {
        cout<<f<<endl;
        count = count + 1;
    }
    if(f==n)
      return 0;
    factors(n, count, f+1); 
    return 0;
}
int main()
{
    int n,t;
    cin>>t;
    while(t--)
    {
            cin>>n;
            int count = 0;
            factors(n, count);
            cout << count << endl;
    }
    return 0;
}

-高拉夫

首先,为什么要在全局空间中声明计数变量?

其次,您不能对未声明的变量执行算术运算(在这种情况下,从不声明 int "count")。

第三,为什么要通过做 while(t--) 创建一个无限循环?

您说该函数将所有输入计数为 0,这可能是由于计数从未被宣布吗?