Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Sieve of Eratosthenes algorithm
  • Loading branch information
Michal Zarnecki committed Aug 15, 2024
commit 544c1f534a2ee29efd7c5bd87b6a5a9bf489f292
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]);
}
}