PHP - check if number is prime

后端 未结 18 1879
野趣味
野趣味 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:25

    You can print "Prime" as a return to the function to ensure nothing is printed during the function except for the condition for "NOT prime".

       class IsPrime
        {       
            function check($num)
            {
                for ($i = 2; $i < $num; $i++)
                {
                    if ($num % $i == 0) 
                    {
                        echo 'NOT prime';
                        break;
                    }               
                }
              return "Prime";         
            }       
        }
    
        $x = new IsPrime();
        echo $x->check(4);
    

提交回复
热议问题