imajinyun /
leetcode-php
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace leetcode; |
||
| 6 | |||
| 7 | class CountPrimes |
||
| 8 | { |
||
| 9 | public static function countPrimes(int $n): int |
||
| 10 | { |
||
| 11 | if ($n <= 1) { |
||
| 12 | return 0; |
||
| 13 | } |
||
| 14 | [$cnt, $arr] = [0, array_fill(0, $n, false)]; |
||
| 15 | for ($i = 2; $i < $n; $i++) { |
||
| 16 | if (!$arr[$i]) { |
||
| 17 | $cnt++; |
||
| 18 | for ($j = 2; $i * $j < $n; $j++) { |
||
| 19 | $arr[$i * $j] = true; |
||
| 20 | } |
||
| 21 | } |
||
| 22 | } |
||
| 23 | |||
| 24 | return $cnt; |
||
| 25 | } |
||
| 26 | |||
| 27 | public static function countPrimes2(int $n): int |
||
| 28 | { |
||
| 29 | if ($n <= 2) { |
||
| 30 | return 0; |
||
| 31 | } |
||
| 32 | $dp = array_fill(0, $n, 1); |
||
| 33 | $dp[0] = $dp[1] = 0; |
||
| 34 | for ($i = 2; $i < $n; $i++) { |
||
| 35 | if ($dp[$i]) { |
||
| 36 | for ($j = $i * $i; $j < $n; $j += $i) { |
||
| 37 | $dp[$j] = 0; |
||
| 38 | } |
||
| 39 | } |
||
| 40 | } |
||
| 41 | |||
| 42 | return array_sum($dp); |
||
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
| 43 | } |
||
| 44 | } |
||
| 45 |