PHP - check if number is prime

后端 未结 18 1811
野趣味
野趣味 2021-01-25 00:03

I\'m trying to create a function which checks whether the number is prime or not. BUT I want this function to echo to the user \'prime\' or \'NOT prime\' - and that\'s where my

18条回答
  •  不要未来只要你来
    2021-01-25 00:43

    This could be a long procedure if the number is really a prime number. There is a shorter procedure as well. We need not run the for loop upto the number itself. Instead, we can run it upto the Highest Integer less than or equal to the square root of the number.

    class IsPrime
    {       
         function check($num)
         {
            $bCheck = True;
    
    
            $highestIntegralSquareRoot = floor(sqrt($num));
            for ($i = 2; $i <= $highestIntegralSquareRoot; $i++)
            {
                if ($num % $i == 0) 
                {
                     $bCheck = False;
                     break;
                }               
            }
           if $bCheck 
              echo 'Prime';           
           else
              echo 'NOT prime'; 
         }       
      }
    
     $x = new IsPrime();
     $x->check(97);
    

    Now, in the above, if we check check whether 97 is prime or not (actually, it is), then the loop need not run from 2 to 97, but only from 2 to 9. (Square root of 97 is 9.8488578018, and highest integer less than or equal to that is 9. Similarly, we can check for number 121 (this is not a prime number, as it is divisible by 11). The limit will be increased from 2 to 11 in a similar matter. And so on. Actually, we need to check the divisibility of the number by the smaller prime numbers in the vicinity, but that would be more complex. Hope this helps.

提交回复
热议问题