Why my function code doesn't add first call of solution when it returns? it adds all recursive function calls solutions but not first

Viewed 12

I'm solving the question, Given an integer N. Calculate the sum of series 13 + 23 + 33 + 43 + … till N-th term.

I write this code but it can't add the first recursive function call solution.

Ex -

N = 5 and the Answer is 1^3+2^3+3^3+4^3+5^3=225. but it gives me 224, it doesn't add the first 1, Is any changes required here?

using namespace std;

long long calSum(long long i,long long n)
{
    int sum = 0;
    if (i > n)
        return 0;

    sum = pow(i,3);
    
    return sum + calSum(i + 1,n);
}

int main()
{

    int n;

    cin >> n;

    cout << calSum(1,n) <<endl;

    return 0;
}
 
1 Answers

I added a debug line after the sum: sum = pow(i,3); printf("pow(%lld,3)=%f\n", i, pow(i,3));

Then ompiled it, and ran with 5:

5
pow(1,3)=1.000000
pow(2,3)=8.000000
pow(3,3)=27.000000
pow(4,3)=64.000000
pow(5,3)=125.000000
225
Related