Skip to content

Commit f57991b

Browse files
Added Project Euler's problem 10 (#110)
* feat:add Project Euler problem 10 * chore:add problem in DIRECTORY
1 parent 1914ea1 commit f57991b

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
* [Problem7](./Maths/ProjectEuler/Problem7.php)
4646
* [Problem8](./Maths/ProjectEuler/Problem8.php)
4747
* [Problem9](./Maths/ProjectEuler/Problem9.php)
48+
* [Problem10](./Maths/ProjectEuler/Problem10.php)
4849

4950
## Searches
5051
* [Binarysearch](./Searches/BinarySearch.php)

Maths/ProjectEuler/Problem10.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
/*
3+
* This function solves the problem 10 of the Project Euler.
4+
*
5+
* Problem description:
6+
* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
7+
* Find the sum of all the primes below two million.
8+
*/
9+
10+
/**
11+
* @return int
12+
*/
13+
function problem10(): int
14+
{
15+
//Using Sieve of Erastothenes
16+
//@see https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
17+
18+
$n = 2000000;
19+
$isPrime = [];
20+
21+
for ($i = 2; $i <= $n; $i++){
22+
$isPrime[$i] = $i;
23+
}
24+
25+
for ($i = 2; $i*$i <= $n; $i++){
26+
if (isset ($isPrime[$i])){
27+
for ( $j = $i; $i*$j <= $n; $j++)
28+
unset($isPrime[$i*$j]);
29+
}
30+
}
31+
32+
return array_sum($isPrime);
33+
}

tests/Maths/ProjectEulerTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
require_once __DIR__ . '/../../Maths/ProjectEuler/Problem7.php';
1313
require_once __DIR__ . '/../../Maths/ProjectEuler/Problem8.php';
1414
require_once __DIR__ . '/../../Maths/ProjectEuler/Problem9.php';
15+
require_once __DIR__ . '/../../Maths/ProjectEuler/Problem10.php';
1516

1617
class ProjectEulerTest extends TestCase
1718
{
@@ -61,4 +62,9 @@ public function testProblem9(): void
6162
$this->assertSame(31875000, problem9());
6263
}
6364

65+
public function testProblem10(): void
66+
{
67+
$this->assertSame(142913828922, problem10());
68+
}
69+
6470
}

0 commit comments

Comments
 (0)