Computer Science Canada

Basic Prime Function Help

Author:  compstudent [ Tue Mar 15, 2011 9:20 pm ]
Post subject:  Basic Prime Function Help

Hi,

I am just starting learning PHP and I have tried to make this Prime Number function. I know it is redundant and not efficient. It also has a little HTML form, but whenever I run the function it says you cannot divide by zero in a big error box on the web browser (through easyPHP)

Here is the code

function findPrime($number)
{
$no=true;
$i=2;
while($i<$number)
{
if ($number % $i = 0)
{
$no=false;
return $no;
}
$i++;
}
if ($no != false)
{
$no=true;
return $no;
}
}

if (findPrime($num1))
{
echo $num1 . " is a prime number.";
}
else
{
echo $num1 . " is not a prime number.";
}
if (findPrime($num2))
{
echo $num2 . " is a prime number.";
}
else
{
echo $num2 . " is not a prime number.";
}


Thanks!

Author:  apython1992 [ Wed Mar 16, 2011 8:53 am ]
Post subject:  RE:Basic Prime Function Help

I'll admit I've never used PHP before, but a quick google search tells me that the comparison operator '==' is used to test for equality, like many other languages. You instead used '=', which actually assigns the value 0 to $i, resulting in the zero division error. Aside from this, I think you'll quickly discover that your function won't actually correctly determine whether or not a number is prime. But that's okay! Learning is a good thing, and you can find lots of help here.

Author:  DemonWasp [ Wed Mar 16, 2011 9:12 am ]
Post subject:  RE:Basic Prime Function Help

PHP has some wacky rules on operator precedence. See here for details: http://www.tuxradar.com/practicalphp/3/12/7

Long story short, the expression "$number % $i = 0" is evaluated as "$number % ( $i = 0 )", even though you meant "($number % $i) == 0".

Author:  compstudent [ Wed Mar 16, 2011 1:26 pm ]
Post subject:  Re: Basic Prime Function Help

Okay - thats good to know- thanks a lot.


: