Skip to content

Commit ee2becc

Browse files
author
Gonzalo Diaz
committed
[Hacker Rank]: Project Euler #1: Multiples of 3 and 5 solved ✓
1 parent 6aa7267 commit ee2becc

File tree

3 files changed

+93
-0
lines changed

3 files changed

+93
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# [Multiples of 3 and 5](https://www.hackerrank.com/contests/projecteuler/challenges/euler001)
2+
3+
- Difficulty: #easy
4+
- Category: #ProjectEuler+
5+
6+
If we list all the natural numbers below $ 10 $ that are multiples of
7+
$ 3 $ or $ 5 $, we get $ 3, 5, 6 $ and $ 9 $.
8+
The sum of these multiples
9+
is $ 23 $.
10+
11+
Find the sum of all the multiples of $ 3 $ or $ 5 $ below $ N $.
12+
13+
## Input Format
14+
15+
First line contains $ T $ that denotes the number of test cases.
16+
This is followed by $ T $ lines, each containing an integer, $ N $.
17+
18+
## Constraints
19+
20+
- 1 $ \leq T \leq 10^5 $
21+
- 1 $ \leq N \leq 10^9 $
22+
23+
## Output Format
24+
25+
For each test case, print an integer that denotes the sum of all the multiples
26+
of $ 3 $ or $ 5 $ below $ N $.
27+
28+
## Sample Input 0
29+
30+
```text
31+
2
32+
10
33+
100
34+
```
35+
36+
## Sample Output 0
37+
38+
```text
39+
23
40+
2318
41+
```
42+
43+
## Explanation 0
44+
45+
For $ N = 10 $, if we list all the natural numbers below $ 10 $ that are
46+
multiples of $ 3 $ or $ 5 $, we get $ 3, 5, 6 $ and $ 9 $.
47+
The sum of these multiples is $ 23 $.
48+
49+
Similarly for $ N = 100 $, we get $ 2318 $.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# pylint: disable=C0103:invalid-name
2+
3+
import math
4+
5+
6+
# Function to find sum of Arithmetic Progression series
7+
def sum_ap(n: int, d: int):
8+
9+
# Number of terms
10+
n = n//d
11+
12+
return (n) * (1 + n) * d // 2
13+
14+
15+
# Function to find the sum of all multiples of a and b below n
16+
def euler001(a, b, n):
17+
18+
# Since, we need the sum of multiples less than N
19+
n = n-1
20+
lcm = (a*b)//math.gcd(a, b)
21+
22+
return sum_ap(n, a) + \
23+
sum_ap(n, b) - \
24+
sum_ap(n, lcm)
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import unittest
2+
from .euler001 import euler001
3+
4+
5+
class TestEuler001(unittest.TestCase):
6+
7+
def test_euler001(self):
8+
9+
tests = [
10+
{'a': 3, 'b': 5, 'n': 10, 'answer': 23},
11+
{'a': 3, 'b': 5, 'n': 100, 'answer': 2318},
12+
{'a': 3, 'b': 5, 'n': 1000, 'answer': 233168}
13+
]
14+
15+
for _, _tt in enumerate(tests):
16+
17+
self.assertEqual(
18+
euler001(_tt['a'], _tt['b'], _tt['n']), _tt['answer'],
19+
f"{_} | euler001({_tt['a']}, {_tt['b']}, {_tt['n']}) must be "
20+
f"=> {_tt['answer']}")

0 commit comments

Comments
 (0)