Last active
December 30, 2020 17:56
-
-
Save drupol/cb6a4bb77bd13f5e7ffe483c770273cc to your computer and use it in GitHub Desktop.
Generating Prime Numbers with loophp/collection
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
<?php | |
declare(strict_types=1); | |
include __DIR__ . '/../vendor/autoload.php'; | |
use loophp\collection\Collection; | |
$integers = Collection::unfold(static fn (int $n = 1): int => $n + 1); | |
$primes = static function (Collection $collection) use (&$primes): Generator { | |
yield $current = $collection->current(); | |
return yield from $primes($collection->filter(static fn (int $i): bool => 0 !== $i % $current)); | |
}; | |
$primesCollection = Collection::fromIterable($primes($integers)); | |
foreach ($primesCollection->limit(100) as $prime) { | |
var_dump($prime); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment