print the sum of the first n cubes

hey, guys for some reason i can't get sum3 and sum4 to print 225 which the sum of first 5 integers when n is 5.
the formula for sum3 is (1+2+3..n)^2and sum4 is n(n+1)(2n+1)/4+2
if anyone could point me in the right direction, i would very much appreciate it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  /*
*/
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double n = 5;
    double sum1 = 0; 
    double sum2 = 0; 
    double sum3 = 0; 
    double sum4 = 0;
    double counter = 1;
    
    while(counter <= n){
   
               sum1 = sum1 + pow(counter,3);
               sum3 = sum3 + pow(counter,2);
               counter++;
}              
   
               sum2 = (pow(n,2)*pow((n + 1),2)) / 4;
               sum4 = sum4 + n*(n + 1) * (2 * n + 1)/(4+2);
               
     cout << "sum1 = "<< sum1 << endl;
     cout << "sum2 = "<< sum2 << endl;   
     cout << "sum3 = "<< sum3 << endl;
     cout << "sum4 = "<< sum4 << endl;
     if(sum1 == sum2)
             cout << "sum1 and sum2 are equal" << endl;
     else
             cout << "sum3 and sum4 are NOT equal" << endl;
     if(sum2 == sum3)
             cout << "sum2 and sum3 are equal" << endl;
     else 
             cout << "sum2 and sum3 are NOT equal" << endl;
     if(sum3 == sum4)
             cout << "sum3 and sum4 are equal" << endl;
     else
             cout << " sum3 and 4 are NOT equal" << endl;
         
     system("pause");
     return 0;
}
24
25
26
               sum4 = sum4 + n*(n + 1) * (2 * n + 1)/(4+2); // might as well be...
               sum4 = sum4 + n*(n + 1) * (2 * n + 1)/6; // so maybe you wanted this:
               sum4 = sum4 + n*(n + 1) * (2 * n + 1)/4 + 2;


Also the calculation of sum3 is incorrect.

You are supposed to do:
(1 + 2 + 3 + ... + n)2

but you are doing:
0 + 12 + 22 + 32 + ... + n2
thanks a bunch, catfish. i got sum3 but sum4 is still giving me trouble. i'm just gonna sleep on it and come back to it tomorrow. but 1 more question i was getting sum3 wrong because i didn't get the sum of first n integers out of the loop before i squared it, right?
but 1 more question i was getting sum3 wrong because i didn't get the sum of first n integers out of the loop before i squared it, right?

You were squaring each of the n integers individually, instead of squaring their sum.
One is not the same as the other:

12 + 22 + 32 = 1 + 4 + 9 = 14

(1 + 2 + 3)2 = 62 = 36
Topic archived. No new replies allowed.