Last active
March 26, 2017 09:37
-
-
Save stoimen/640e6c0492d50904f3d6 to your computer and use it in GitHub Desktop.
Determine if a Number is Prime
This file contains hidden or 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 | |
function eratosthenes_sieve(&$sieve, $n) { | |
$i = 2; | |
while ($i <= $n) { | |
if ($sieve[$i] == 0) { | |
echo $i; | |
$j = $i; | |
while ($j <= $n) { | |
$sieve[$j] = 1; | |
$j += $i; | |
} | |
} | |
$i++; | |
} | |
} | |
$n = 100; | |
$sieve = array_fill(0, $n, 0); | |
// 2, 3, 5, 7, ..., 97 | |
eratosthenes_sieve($sieve, $n); | |
?> |
This file contains hidden or 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 | |
function isPrime($n) { | |
$i = 2; | |
if ($n == 2) { | |
return true; | |
} | |
while ($i < $n) { | |
if ($n % $i == 0) { | |
return false; | |
} | |
$i++; | |
} | |
return true; | |
} | |
// prints the prime numbers between 2 and 100 | |
// 3, 5, 7, ..., 97 | |
for ($i = 3; $i < 100; $i++) { | |
if (isPrime($i)) { | |
echo $i; | |
} | |
} | |
?> |
This file contains hidden or 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 | |
function isPrime($n) { | |
$i = 2; | |
if ($n == 2) { | |
return true; | |
} | |
while ($i <= $n/2) { | |
if ($n % $i == 0) { | |
return false; | |
} | |
$i++; | |
} | |
return true; | |
} | |
?> |
This file contains hidden or 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 | |
function isPrime($n) { | |
$i = 2; | |
if ($n == 2) { | |
return true; | |
} | |
$sqrtN = sqrt($n); | |
while ($i <= $sqrtN) { | |
if ($n % $i == 0) { | |
return false; | |
} | |
$i++; | |
} | |
return true; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment