Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sieve of Eratosthenes algorithm #159

Merged
merged 1 commit into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
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]);
}
}
Loading