ClavinJune

Print N of First Prime Number

Sep 30th, 2017
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.62 KB | None | 0 0
  1. #! /usr/bin/php
  2. <?php
  3. function isPrime($num){
  4.     if( $num < 2 ) return false;
  5.     for( $i=2;$i<=$num**0.5;++$i )
  6.         if( !($num%$i) ) return false;
  7.     return true;
  8. }
  9. function printFirstNPrime($N, $start = 2, $count = 0){
  10.     if( $count == $N ) return;
  11.     if( isPrime($start) ){
  12.         ++$count;
  13.         echo $start . ' ';
  14.     }
  15.     printFirstNPrime($N, ++$start, $count);
  16. }
  17. //kalau printFirstNPrime(1); cuma munculin 2
  18. //kalau printFirstNPrime(2); cuma munculin 2 3
  19. //kalau printFirstNPrime(3); cuma munculin 2 3 5
  20. //kalau printFirstNPrime(4); cuma munculin 2 3 5 7
  21. //kalau printFirstNPrime(5); cuma munculin 2 3 5 7 11
  22. printFirstNPrime(5);
Add Comment
Please, Sign In to add comment