A
A
alphasigma2014-06-01 00:15:50
Mathematics
alphasigma, 2014-06-01 00:15:50

How to calculate the sum of numbers on the interval from a to b, without a loop?

Faced this problem for a long time and still does not give rest. It is clear that it is time-consuming to solve this with a cycle, but I also found another way out - an arithmetic progression, but here it starts not from 1, but from an arbitrary element, so here the standard formula will not work.
I specify the question:
How to mathematically calculate the sum, for example, from 47 to 72, i.e. 47 + 48+ 49 ... + 72 ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
ManWithBear, 2014-06-01
@alphasigma

Here is the standard formula.
S = (a1+an)*n/2, where a1 is the first member, an is the last, n is the number of members of the sequence
We have (47+72)*26/2 = 1547
Total your formula: S = (a+b) (b-a+1)/2

A
Andrew, 2014-06-01
@OLS

result = ((b+1)*b-(a-1)*a) div 2;
a=1 b=100 result=5050 (that's how much it should be, not 1050)
a=2 b=5 result=14 (2+3+4+5=14)
a=5 b=10 result=45 ( 5+6+7+8+9+10=45)

V
Vladlen Grachev, 2014-06-01
@gwer

How to mathematically calculate the sum, for example, from 47 to 72, i.e. 47 + 48+ 49 ... + 72 ?

Calculate the sum of the first 72 terms of the arithmetic progression and subtract from it the sum of the first 46 terms of the arithmetic progression.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question