Find the sum of all multiples of 2 and 5 below N
Given a number N. and the task is to find the sum of all multiples of 2 and 5 below N ( N may be up to 10^10).
Examples:
Input : N = 10
Output : 25
Explanation : 2 + 4 + 6 + 8 + 5
Input : N = 20
Output : 110
Approach :
We know that multiples of 2 form an AP as:
2, 4, 6, 8, 10, 12, 14….(1)
Similarly, multiples of 5 form an AP as:
5, 10, 15……(2)
Now, Sum(1) + Sum(2) = 2, 4, 5, 6, 8, 10, 10, 12, 14, 15….
Here, 10 is repeated. In fact, all of the multiples of 10 or 2*5 are repeated because it is counted twice, once in the series of 2 and again in the series of 5. Hence we’ll subtract the sum of the series of 10 from Sum(1) + Sum(2).
The formula for the sum of an A.P is :
n * ( a + l ) / 2
Where is the number of terms, is the starting term, and is the last term.
So, the final answer is:
S2 + S5 – S10
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long sumAP( long long n, long long d)
{
n /= d;
return (n) * (1 + n) * d / 2;
}
long long sumMultiples( long long n)
{
n--;
return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);
}
int main()
{
long long n = 20;
cout << sumMultiples(n);
return 0;
}
|
C
#include <stdio.h>
long long sumAP( long long n, long long d)
{
n /= d;
return (n) * (1 + n) * d / 2;
}
long long sumMultiples( long long n)
{
n--;
return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);
}
int main()
{
long long n = 20;
printf ( "%lld" ,sumMultiples(n));
return 0;
}
|
Java
class GFG{
static long sumAP( long n, long d)
{
n /= d;
return (n) * ( 1 + n) * d / 2 ;
}
static long sumMultiples( long n)
{
n--;
return sumAP(n, 2 ) + sumAP(n, 5 ) - sumAP(n, 10 );
}
public static void main(String[] args)
{
long n = 20 ;
System.out.println(sumMultiples(n));
}
}
|
Python3
def sumAP(n, d):
n = int (n / d);
return (n) * ( 1 + n) * (d / 2 );
def sumMultiples(n):
n - = 1 ;
return ( int (sumAP(n, 2 ) + sumAP(n, 5 ) -
sumAP(n, 10 )));
n = 20 ;
print (sumMultiples(n));
|
C#
using System;
public class GFG{
static long sumAP( long n, long d)
{
n /= d;
return (n) * (1 + n) * d / 2;
}
static long sumMultiples( long n)
{
n--;
return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);
}
static public void Main (){
long n = 20;
Console.WriteLine(sumMultiples(n));
}
}
|
PHP
<?php
function sumAP( $n , $d )
{
$n = (int)( $n / $d );
return ( $n ) * ((1 + $n ) *
(int) $d / 2);
}
function sumMultiples( $n )
{
$n --;
return sumAP( $n , 2) + sumAP( $n , 5) -
sumAP( $n , 10);
}
$n = 20;
echo sumMultiples( $n );
?>
|
Javascript
<script>
function sumAP(n, d)
{
n = parseInt(n / d);
return (n) * ((1 + n) *
parseInt(d) / 2);
}
function sumMultiples(n)
{
n--;
return sumAP(n, 2) + sumAP(n, 5) -
sumAP(n, 10);
}
n = 20;
document.write( sumMultiples(n));
</script>
|
Time complexity: O(1), since there is no loop or recursion.
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
27 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...