find the sum of (1+2+...n)^2

I am trying to figure out what went wrong in my formula for sum2. It should be equal to sum1, which is equal to 784. The formula for sum2 = (1 + 2 + … + n)^2. Currently with this code I get sum2 is equal to 140. Can anyone tell me how I should fix this problem? Or give a hint

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
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double n = 7;
    double sum1 = 0; 
    double sum2 = 0; 
    double sum3 = 0; 
    double sum4 = 0;
    double i = 1;
    
    while(i <= n){
   
               sum1 = sum1 + pow(i,3);
               sum2 = sum2 + (i)*(i);
               i++;
}             
   
               sum3 = (pow(n,2)*pow((n + 1),2)) / 4;
               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 << endl;


   system("PAUSE");
   return 0;
}
Last edited on
Your formula for sum2 is off, I think. The way you have sum2 right now is sum2 = (1^2 + 2^2 + ...), while sum1 = (1^3 + 2^3 + ...).

If you do want sum2 = (1 + 2 + ... + n)^2, just do

1
2
3
4
5
6
7
while( i <= n)
   {
      sum2 += i;
   }

sum2 = pow(sum2,2);
Last edited on
thank you! it worked, I feel kind of silly now for not thinking of it that way
(N(N + 1) / 2)2
Look up Gauss and arithmetic series
Topic archived. No new replies allowed.