Given a number a and limit N. Find the sum of multiple of a upto N.
Input : a = 4, N = 23 Output : sum = 60 [Multiples : 4, 8, 12, 16, 20] Input :a = 7, N = 49 Output :sum = 196 [Multiples: 7, 14, 21, 28, 35, 42, 49]
The basic idea is to iterate from i = a to i = n, i++ and check whether i % a == 0 or not.If zero then add i to sum(initially sum = 0).Thus we will get the sum.It will take O(n) time.
We can modify the loop as i = a, i <= n, i = i + a to reduce the number of iterations.But it will also take O(m) time if there is m multiples of a.
To get the result in O(1) time we can use the formula of summation of n natural numbers.For the above example,
a = 4 and N = 23, number of multiples of a, m = N/a(integer division). The multiples are 4, 8, 12, 16, 20.
We can write it as 4 X [1, 2, 3, 4, 5]. So we can get the sum of multiples as:
sum = a * (Summation of 1 to m [natural numbers from 1 to m]) sum = 4 * (m*(m+1) / 2) sum = 4 * (5*6 / 2) = 4 * 15 = 60
Sum of multiples of 7 upto 49 = 196
This article is contributed by Sukanta Nandi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.