Answer the question
In order to leave comments, you need to log in
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
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. a + N*k > b
var N = 1 + Math.floor((b-a) / k);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question