R
R
Ruslan Askarov2020-01-14 19:14:06
Mathematics
Ruslan Askarov, 2020-01-14 19:14:06

How to calculate the sum of numbers on the interval a, b with step k without a loop?

It is required to find the sum of numbers from a to b without using for, while, etc. loops. The only solution, as I understand it, is the arithmetic progression formula. But how to supplement this formula so that it counts with a step?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2020-01-14
@askrus97

You can represent the sum of this sequence with step k as follows:

(a + 0*k) + (a + 1*k) + (a + 2*k) + ... + (a + (N-1)*k)
= a * N + ( 0*k + 1*k + 2*k + ... (N-1)*k )
= a * N + k * (0 + 1 + 2 + ... (N-1))
= a * N + k * (N * (N - 1) / 2 )
The result was a formula for the desired amount.
It remains to find N - the number of summed numbers \u003d the minimum N, at which a + N*k > b
programming will help here: We got N, calculated the sum using the formula. No cycles, one rounding)var N = 1 + Math.floor((b-a) / k);

B
beerchaser, 2020-01-14
@beerchaser

In principle, you can also use recursion

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question