Indeed, there is a solution O (1):
First, perform integer arithmetic to calculate n = N / M n is the number of members in arithmetic progression with the first member and the total difference equal to M
The sum (which comes from the formula for arithmetic progression) then
n * (1 + n) * M / 2
For example, consider N = 23 and M = 5. You get 5 + 10 + 15 + 20, which is equal to 50. A closed form solution is estimated at 4 * 5 * 5/2, which is also equal to 50.
source share