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
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);
<?php
function primeCheck($num)
{
if ($num == 1)
return false;
for ($i = 2; $i <= $num/2; $i++)
{
if ($num % $i == 0)
{
return false;
}
}
return true;
}
$primeNumber = primeCheck(17);
if ($primeNumber == true)
{
echo "Is Prime";
}
else
{
echo "Is Not Prime";
}
?>
Please Check this
class IsPrime
{
function check($num)
{
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
return 'NOT prime';
}
}
return 'Prime';
}
}
$x = new IsPrime();
$result = $x->check(4);
echo $result;
function is_prime($number)
{
return (bool) !preg_match('/^1?$|^(11+?)\1+$/x', str_repeat('1', $number));
}
You can check number is prime or not & without using loop with this function:
function is_prime($p) {
$r1 = $p%2;
$r2 = $p%3;
$r3 = $p%5;
return ($p > 1) && (($r1 >= 1) && ($r2 >= 1) && ($r3 >= 1)) || in_array($p, [2,3,5]);
}
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);