Skip to content

Commit 16be0f2

Browse files
mzarneckiMichal Zarnecki
and
Michal Zarnecki
authored
Sieve of Eratosthenes algorithm (#159)
Co-authored-by: Michal Zarnecki <[email protected]>
1 parent e679135 commit 16be0f2

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

DIRECTORY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
* [Problem7](./Maths/ProjectEuler/Problem7.php)
5858
* [Problem8](./Maths/ProjectEuler/Problem8.php)
5959
* [Problem9](./Maths/ProjectEuler/Problem9.php)
60+
* [Eratosthenessieve](./Maths/EratosthenesSieve.php)
6061

6162
## Searches
6263
* [Binarysearch](./Searches/BinarySearch.php)
@@ -119,6 +120,7 @@
119120
* Maths
120121
* [Mathstest](./tests/Maths/MathsTest.php)
121122
* [Projecteulertest](./tests/Maths/ProjectEulerTest.php)
123+
* [Eratosthenessievetest](./tests/Maths/EratosthenesSieveTest.php)
122124
* Searches
123125
* [Searchestest](./tests/Searches/SearchesTest.php)
124126
* Sorting

Maths/EratosthenesSieve.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
/**
4+
* The Sieve of Eratosthenes is an algorithm is an ancient algorithm for finding all prime numbers up to any given limit
5+
* https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
6+
*
7+
* @author Michał Żarnecki https://github.com/rzarno
8+
* @param int $number the limit of prime numbers to generate
9+
* @return string[] prime numbers up to the given limit
10+
*/
11+
function eratosthenesSieve(int $number): array
12+
{
13+
$primes = range(1, $number);
14+
$primes = array_combine($primes, $primes);
15+
$limit = sqrt($number);
16+
$current = 2;
17+
while ($current < $limit) {
18+
$multiplied = $current;
19+
$factor = 1;
20+
while ($multiplied < $number) {
21+
$factor++;
22+
$multiplied = $current * $factor;
23+
if (isset($primes[$multiplied])) {
24+
unset($primes[$multiplied]);
25+
}
26+
}
27+
$current += 1;
28+
}
29+
return array_values($primes);
30+
}

tests/Maths/EratosthenesSieveTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
require_once __DIR__ . '/../../vendor/autoload.php';
4+
require_once __DIR__ . '/../../Maths/EratosthenesSieve.php';
5+
6+
use PHPUnit\Framework\TestCase;
7+
8+
class EratosthenesSieveTest extends TestCase
9+
{
10+
public function testEratosthenesSieve()
11+
{
12+
$result = eratosthenesSieve(30);
13+
14+
$this->assertEquals($result, [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
15+
}
16+
}

0 commit comments

Comments
 (0)