Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count sum of multiples of a number below N with O(1) complexity?

We are given two numbers M and N. We need to count the sum of all the integers below N, which are divisible by M.

Is it possible to solve with O(1) complexity?

I know it is a very simple program and can be easily done with a loop. But I was wondering if it is possible to apply some kind of formula or something to directly count the sum of numbers which are divisible by M below N.

like image 295
VatsalSura Avatar asked Jul 08 '16 12:07

VatsalSura


2 Answers

Indeed there is an O(1) solution:

First exploit integer arithmetic to compute n = N / M. n is then the number of terms in an arithmetic progression with first term and common difference equal to M.

The sum (which comes from the formula for an arithmetic progression) is then

n * (1 + n) * M / 2

For example, consider N = 23, and M = 5. You're after 5 + 10 + 15 + 20 which is 50. The closed form solution evaluates to 4 * 5 * 5 / 2 which is also 50.

like image 138
Bathsheba Avatar answered Oct 19 '22 09:10

Bathsheba


L:=floor(M/N)

M + 2*M + 3*M + ... + L*M 

= M (1+2+3+4+...+L)

this can be solved with the wikipedia summation

= M*(L*(L+1)/2)

This can be calculated in O(1)

like image 28
MrSmith42 Avatar answered Oct 19 '22 08:10

MrSmith42