Question

Here is my code for printing the divisors and then number of divisors of a given number.

Now suppose I take 2 test cases: 5 and 8; this code gives count of 5 as 2 and 8 as 6 (i.e it adds the previous count).

Even if I declare it as int count = 0; it returns the same output.

The other problem arises when I declare int count = 0 inside function factors.

The code gives count as 0 for all cases.

#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;
}
Was it helpful?

Solution

Using globals is not usually a good idea. It is especially bad in recursive functions, which should preferably be re-entrant. Of course you can fix your function by resetting the count in the loop, like this:

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

You could also make factors "wrapper" that resets the count to free the callers from the need to reset count before calling factors, like this:

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
}

OTHER TIPS

you can achieve this by passing count as reference -

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

-Gaurav

First, why are you declaring the count variable in the global space?

Second, you can not perform arithmetic operations to an undeclared variable (the int "count" in this case is never declared).

Third, why do you create an infinite loop by doing while(t--)?

You said the function gives you count as 0 for all input, Can this be due to count never being declared?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top