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

27th May 2019, 7:24 AM
Yuri Kurashov
Yuri Kurashov - avatar
1 Odpowiedź
+ 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.
27th May 2019, 2:28 PM
Denise Roßberg
Denise Roßberg - avatar