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
As many answer pointed out, your logic code has a problem: when you get i
such that num % i == 0
, you print "NOT prime" and quit the loop, after that, you still print "Prime". Some guys moved echo "Prime"
in if-else
, it is still wrong. One way to approach, for example,
class IsPrime
{
function check($num)
{
$bCheck = True;
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
$bCheck = False;
break;
}
}
if $bCheck
echo 'Prime';
else
echo 'NOT prime';
}
}
$x = new IsPrime();
$x->check(4);