Sum of multiples of a number up to N
Last Updated :
09 Jun, 2022
Given a number a and limit N. Find the sum of multiple of a upto N.
Examples :
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
C++
#include <iostream>
using namespace std;
int calculate_sum( int a, int N)
{
int m = N / a;
int sum = m * (m + 1) / 2;
int ans = a * sum;
return ans;
}
int main()
{
int a = 7, N = 49;
cout << "Sum of multiples of "
<< a << " up to " << N << " = "
<< calculate_sum(a, N) << endl;
return 0;
}
|
Java
class GFG {
static int calculate_sum( int a, int N) {
int m = N / a;
int sum = m * (m + 1 ) / 2 ;
int ans = a * sum;
return ans;
}
public static void main(String[] args) {
int a = 7 , N = 49 ;
System.out.println( "Sum of multiples of " + a +
" up to " + N + " = " +
calculate_sum(a, N));
}
}
|
Python3
C#
PHP
<?php
function calculate_sum( $a , $N )
{
$m = $N / $a ;
$sum = $m * ( $m + 1) / 2;
$ans = $a * $sum ;
return $ans ;
}
$a = 7;
$N = 49;
echo "Sum of multiples of " . $a ,
" up to " . $N . " = " .
calculate_sum( $a , $N ) ;
?>
|
Javascript
<script>
function calculate_sum(a, N)
{
m = N / a;
sum = m * (m + 1) / 2;
ans = a * sum;
return ans;
}
let a = 7;
let N = 49;
document.write( "Sum of multiples of " + a +
" up to " + N + " = " +
calculate_sum(a, N));
</script>
|
Output :
Sum of multiples of 7 upto 49 = 196
Time complexity: O(1)
Auxiliary space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...