I'm looking for a method like calculation:
function sumIntegerUpTo (number ) {Return 1 + 2 + 3 + ... + number; }
If you have the 5
function as the number
as the function of 1 + 2 + 3 + 4 + 5 Should return
. I am thinking that it is possible to do this without loop.
function sumIntegerUpTo (number) {return (1 + number) * number / 2; }
I can think of two easy ways to remember this formula:
-
Add numbers from both ends of the sequence Think about: 1 and N, 2 and N-1, 3 and N-2, etc. Each of these small zodiac sign is equal to N + 1, both end ends in the middle (average) of the sequence, so the total should be 2/2 of them. So yoga = (N + 1) * (N / 2).
-
As many numbers are before the average (that is (1 + n) / 2) later, and after adding a pair of numbers equal to this average, always the average The result is twice, and it contains n / 2, then the sum = (n + 1) / 2 * 2 * n / 2 = (n + 1) / 2 * n.
You can easily expand the above logic in a different beginning number, you give: the number of zodiac (one to b, inclusive) = (A + b) / 2 * (ba + 1)
Comments
Post a Comment