Could someone show me how to add the numbers 1 thru 50 and display the total of 1275 the easy way. My brain wont close in on this one and I dont want to use a ton of variables.
Thanks in advance
trip7
Printable View
Could someone show me how to add the numbers 1 thru 50 and display the total of 1275 the easy way. My brain wont close in on this one and I dont want to use a ton of variables.
Thanks in advance
trip7
you mean something like this?
long count = 0;
for( long i = 0; i <= 50; i++)
count += i;
thats it...Code:int result = 0;
for(int i = 0 ; i < 51 ; i ++ )
{
result += i ;
}
'result' is 1275
sum = (50*51)/2= 25*51
Exactly what I was looking for and thanks for your help all!
P.S.
in general the sum of the numbers from 1 to n is
sum = n*(n+1)/2
and in general to sum the numbers from m to n with 1 <= m < n
sum = (m+n)(m-n+1)/2
proof
write the sum in two ways
sum = m + (m+1) + (m+2) +...+ (n-2) + (n-1) + n
sum = n + (n - 1) + (n - 2)+...+ (m+2) + (m+1) + m
Now add the columns
2*sum = (m+n)+(m+n)+(m+n)+...+(m+n)+(m+n)+(m+n)
How many terms are on the right? (m-n+1)
so
2*sum = (m+n)(m-n+1)
and it done
well i alwasys thought...there is a vast difference between experience+coolness and education...;)Quote:
Originally posted by souldog
sum = (50*51)/2= 25*51
cool Mr.Souldog....expected a cool answer from you like above..;)
now comes the formula.....cool!!!!:cool: :cool:
Of course, there is always a good way and an excellent way of doing something :)