Last active
October 27, 2016 08:41
-
-
Save bishwanathjha/8c7653cc48ee21a573c5464aac05db66 to your computer and use it in GitHub Desktop.
List all the prime numbers less than or equal to a given integer n in PHP
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 | |
/** | |
* @author Bishwanath Jha <bishwanathkj@gmail.com> | |
* Give the nth number as input and it will return all prime numbers less than or equal to that number | |
*/ | |
function GetPrimeNumberList($num) { | |
if ($num == 1) { | |
return $num; | |
} | |
$list = [1]; | |
for($i = 2; $i <= $num; $i++) { | |
for($j = 2; $j < $i/2; $j++) { | |
if($i % $j == 0) break; | |
} | |
if($j == $i ) $list[] = $i; | |
} | |
return $list; | |
} | |
print_r(GetPrimeNumberList(20)); | |
/** | |
Output: | |
Array | |
( | |
[0] => 1 | |
[1] => 2 | |
[2] => 3 | |
[3] => 5 | |
[4] => 7 | |
[5] => 11 | |
[6] => 13 | |
[7] => 17 | |
[8] => 19 | |
) */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment