0
Sum all numbers from 1 to 1 000 000
Hi! There are two ways to sum all numbers from 1 to 1 000 000 in my code. Second way is sum = 1000000 / 2 * (1000000 + 1) Why does it work? Do you know another way to sum all numbers? https://code.sololearn.com/c70Rp71FWT0q/?ref=app
1 Answer
+ 2
I think it was Gauss who fund this way (your second way):
e.g. sum from 1 - 10:
First + last = 11 (1 + 10)
Second + second last (9 + 2 = 11)
...8 + 3 = 11; 7 + 4 = 11; 6 + 5 = 11
-> (1 + 10) * 10/2
-> 11 * 5 = 55
You can do this calculation with all sums from 1 to n.