Skip to content

Commit f99f948

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

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
namespace algorithm_exercises_csharp.hackerrank.prohecteuler;
2+
3+
[TestClass]
4+
public class Euler001Test
5+
{
6+
public class Euler001TestCase {
7+
public int a; public int b; public int n; public int answer;
8+
}
9+
10+
// dotnet_style_readonly_field = true
11+
private static readonly Euler001TestCase[] tests = [
12+
new() { a = 3, b = 5, n = 10, answer = 23},
13+
new() { a = 3, b = 5, n = 100, answer = 2318},
14+
new() { a = 3, b = 5, n = 1000, answer = 233168},
15+
16+
];
17+
18+
[TestMethod]
19+
public void Euler001ProblemTest()
20+
{
21+
int result;
22+
23+
foreach (Euler001TestCase test in tests) {
24+
result = Euler001Problem.Euler001(test.a, test.b, test.n);
25+
Assert.AreEqual(test.answer, result);
26+
}
27+
}
28+
}
29+
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
namespace algorithm_exercises_csharp.hackerrank.prohecteuler;
2+
3+
using System.Diagnostics.CodeAnalysis;
4+
5+
public class Euler001Problem
6+
{
7+
[ExcludeFromCodeCoverage]
8+
protected Euler001Problem() {}
9+
10+
public static int SuOfArithmeticProgression(int n, int d) {
11+
int new_n = n / d;
12+
13+
return new_n * (1 + new_n) * d / 2;
14+
}
15+
16+
public static int GCD(int u, int v)
17+
{
18+
if (v != 0)
19+
{
20+
return GCD(v, u % v);
21+
}
22+
return u;
23+
}
24+
25+
// Function to find the sum of all multiples of a and b below n
26+
public static int Euler001(int a, int b, int n)
27+
{
28+
// Since, we need the sum of multiples less than N
29+
int new_n = n - 1;
30+
int lcm = a * b / GCD(a, b);
31+
32+
return SuOfArithmeticProgression(new_n, a) +
33+
SuOfArithmeticProgression(new_n, b) -
34+
SuOfArithmeticProgression(new_n, lcm);
35+
}
36+
}

0 commit comments

Comments
 (0)