-
-
Notifications
You must be signed in to change notification settings - Fork 469
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sieve of Eratosthenes algorithm (#159)
Co-authored-by: Michal Zarnecki <[email protected]>
- Loading branch information
Showing
3 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | ||
} | ||
} |