Gauss sum

Gauss sum allows to calculate the sum of a succession of consecutive numbers. $\sum\limits_{i=1}^n n = 1 + 2 + 3 + 4 + 5 + \ldots + n = n*(n+1)/2$

Formula

This formula was, according to an anecdote, discovered by the little Gauss-German mathematician-at the age of 9 years. As all the children played (with numbers though) and realized that if we take the same succession of numbers and inver’t, we get this particular result:

1 2 3 4 5
5 4 3 2 1

Starting from a succession beginning from 1 with consecutive terms, Gauss noticed that by summing the terms one by one, the result was always the same, that is always equal to n+1. If we consider that there are n elements and that to make this calculation we have added an extra succession whose sum is the same as the original succession, we get the formula.

In case the succession starts from a number greater than 1 you can calculate the $range as the number of elements between the smallest and the largest and the$value as the sum of the paired terms of the two series, one of which reversed as In the preceding example.

In the event that the terms are not consecutive, but nevertheless equidistant, a multiplier factor may be considered: $\sum\limits_{i=1}^n 3n = 1 + 3 + 6 + 9 + \ldots + 3n = 3*\sum\limits_{i=1}^n n$

Now you try

Choose 1 < endTo < 108 the last term of the succession, 0 < startFrom < 108 the first term, 0 < multiplyBy < 107 the distance betweeen each term.

<?php
function GaussSum($endTo,$startFrom = 1, $multiplyBy = 1) {$range = $endTo -$startFrom + 1;
$value =$endTo + $startFrom; return$multiplyBy*$range*$value/2;
}

$IN = (array) json_decode(base64_decode($argv));
extract($IN); echo GaussSum($endTo, $startFrom,$multiplyBy);
?>

JSON-formatted Input

{
"endTo": 20,
"startFrom": 1,
"multiplyBy": 1
}
210