Skip to content

Commit

Permalink
Sieve of Eratosthenes algorithm (#159)
Browse files Browse the repository at this point in the history
Co-authored-by: Michal Zarnecki <[email protected]>
  • Loading branch information
rzarno and Michal Zarnecki authored Aug 19, 2024
1 parent e679135 commit 16be0f2
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
* [Problem7](./Maths/ProjectEuler/Problem7.php)
* [Problem8](./Maths/ProjectEuler/Problem8.php)
* [Problem9](./Maths/ProjectEuler/Problem9.php)
* [Eratosthenessieve](./Maths/EratosthenesSieve.php)

## Searches
* [Binarysearch](./Searches/BinarySearch.php)
Expand Down Expand Up @@ -119,6 +120,7 @@
* Maths
* [Mathstest](./tests/Maths/MathsTest.php)
* [Projecteulertest](./tests/Maths/ProjectEulerTest.php)
* [Eratosthenessievetest](./tests/Maths/EratosthenesSieveTest.php)
* Searches
* [Searchestest](./tests/Searches/SearchesTest.php)
* Sorting
Expand Down
30 changes: 30 additions & 0 deletions Maths/EratosthenesSieve.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

/**
* The Sieve of Eratosthenes is an algorithm is an ancient algorithm for finding all prime numbers up to any given limit
* https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
*
* @author Michał Żarnecki https://github.com/rzarno
* @param int $number the limit of prime numbers to generate
* @return string[] prime numbers up to the given limit
*/
function eratosthenesSieve(int $number): array
{
$primes = range(1, $number);
$primes = array_combine($primes, $primes);
$limit = sqrt($number);
$current = 2;
while ($current < $limit) {
$multiplied = $current;
$factor = 1;
while ($multiplied < $number) {
$factor++;
$multiplied = $current * $factor;
if (isset($primes[$multiplied])) {
unset($primes[$multiplied]);
}
}
$current += 1;
}
return array_values($primes);
}
16 changes: 16 additions & 0 deletions tests/Maths/EratosthenesSieveTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../Maths/EratosthenesSieve.php';

use PHPUnit\Framework\TestCase;

class EratosthenesSieveTest extends TestCase
{
public function testEratosthenesSieve()
{
$result = eratosthenesSieve(30);

$this->assertEquals($result, [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
}
}

0 comments on commit 16be0f2

Please sign in to comment.