# Math program

• 10-17-2004
KneeGrow
Math program
I don't understand why my program doesn't work... Its supposed to find the sum of:

1*2 + 3*4 + 5*6 ... + 2003*2004
When i output what is being held in array[0] it gives me like 4.022+06 or something whereas it should be 1 and array[1] should be two

Code:

#include <iostream.h>
#include <math.h>

void main() {
int i, j;
double array[1002];
double sum=0;
double square;

for (j=0; j<1002; j++) {
for (i=1; i<=2004; i+=2) {
array[j]=i*(i+1);
}
}

for (i=0; i<1002; i++) {
sum+=array[i];
}
cout<<array[0]<<endl;
cout<<sum<<endl;
}

• 10-17-2004
Salem
Your inner loop does nothing - except to put 2004 * 2005 into every array element
• 10-17-2004
KneeGrow
Oh yeah you're right thanks a lot
• 10-17-2004
KneeGrow
k i fixed it

Code:

for (j=1; j<=1002; j++) {
array[j-1]=(2*j)*(2*j -1);
}

• 10-17-2004
curlious
Code:

for (j=0; j<1002; j++) {
for (i=1; i<=2004; i+=2) {
array[j]+=i*(i+1);
}
}

would this work note you must init the array to zero
• 10-17-2004
Shakti
It would work but why have an array with 1002 elements, that are all the same?
• 10-17-2004
curlious
Code:

int sum(int maxNumber)
{
if (maxNumber<=2) return maxNumber;
return maxNumber*(maxNumber-1)+sum(maxNumber-2);
}

Thought I'd try a recursive solution.
Is this correct. Not very pretty thats for sure.
• 10-17-2004
KneeGrow
well my new and improved code sets

array [0]: 1*2
array [1]: 3*4
array [2]: 5*6

...

array [1002] 2003*2004
• 10-18-2004
just2peachy
Been thinking about your new and improved code. . . I think that the last entry is wrong.

Code:

array[1001]: 2003*2004

Reasoning: each "n" entry of the array should be equal to ([(n+1)*2]-1)*[(n+1)*2]

just2peachy

P.S.
if you look closely at these numbers:
array[0]=1*2=2(1)
array[1]=3*4=2(6)
array[2]=5*6=2(15)
array[3]=7*8=2(28)
.
.
.
Examine the pattern forming. Do you see a special number pattern with 1, 6, 15, 28, . . .

If you've messed around with triangular numbers or hexagonal numbers, you should see some bells and whistles.

Try a google search with triangular numbers. You'll find that each
T(2n+1) or each odd triangular number fitts this pattern. There are many formulas for dealing with the summation of triangular numbers or in this case hexagonal numbers. The summation of these numbers could probably be found with one quick formula.