Advertisement
Ostap34PHP

Untitled

Jun 1st, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.05 KB | None | 0 0
  1. <?php
  2. function solution($count){
  3.     $i = 2;
  4.     $result = 0;
  5.     while($i <= $count){
  6.         if(isPrime($i)){
  7.             $result += $i;
  8.         }
  9.         $i++;
  10.     }
  11.     print $result;
  12.     return $result;
  13. }
  14.  
  15. function isPrime($num) {
  16.     //1 is not prime. See: http://en.wikipedia.org/wiki/Prime_number#Primality_of_one
  17.     if($num == 1)
  18.         return false;
  19.  
  20.     //2 is prime (the only even number that is prime)
  21.     if($num == 2)
  22.         return true;
  23.  
  24.     /**
  25.      * if the number is divisible by two, then it's not prime and it's no longer
  26.      * needed to check other even numbers
  27.      */
  28.     if($num % 2 == 0) {
  29.         return false;
  30.     }
  31.  
  32.     /**
  33.      * Checks the odd numbers. If any of them is a factor, then it returns false.
  34.      * The sqrt can be an aproximation, hence just for the sake of
  35.      * security, one rounds it to the next highest integer value.
  36.      */
  37.     $ceil = ceil(sqrt($num));
  38.     for($i = 3; $i <= $ceil; $i = $i + 2) {
  39.         if($num % $i == 0)
  40.             return false;
  41.     }
  42.  
  43.     return true;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement