ProjectEuler -01 Multiple of 3 and 5
PROBLEM : https://www.hackerrank.com/contests/projecteuler/challenges/euler001
If we list all the natural numbers below
that are multiples of
or
,
we get
and
.
The sum of these multiples is
.
Find the sum of all the multiples of
or
below
.
Input Format
First line contains
that denotes the number of test cases. This is followed by
lines, each containing an integer,
.
Constraints
Output Format
For each test case, print an integer that denotes the sum of all the
multiples of
or
below
.
Sample Input 0
2
10
100
Sample Output 0
23
2318
Explanation 0
For ,
if we list all the natural numbers below
that are multiples of
or
,
we get
and
.
The sum of these multiples is
.
Similarly for ,
we get
.
Solution :
#include <iostream>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--) {
long long int n, x, y, z, m3, m5, m15, sum = 0;
cin >> n;
if (n % 3 == 0)
x = (n - 1) / 3;
else
x = n / 3;
if (n % 5 == 0)
y = (n - 1) / 5;
else
y = n / 5;
if (n % 15 == 0)
z = (n - 1) / 15;
else
z = n / 15;
m3 = (x * ((2 * 3) + (x - 1) * 3)) / 2;
m5 = (y * ((2 * 5) + (y - 1) * 5)) / 2;
m15 = (z * ((2 * 15) + (z - 1) * 15)) / 2;
sum = m3 + m5 - m15;
cout << sum << endl;
sum = 0;
}
return 0;
}
Read other posts