请帮助我使用代码来检查表中的数字是否为素数:这是我的代码。我使用了isPrime函数,但是我得到一个错误,当我在表中调用函数时返回单词“isPime”
<?php
$x="num1";
$y="num2";
if(isset($_POST['Submit'])) {
$start=$_POST['num1'];
$end=$_POST['num2'];
echo "<table width='250' cellpadding='2' cellspacing='4' border='1'>";
echo "<tr><td>Number</td><td>Odd or Even?</td><td>Prime?</td></tr>";
for ($start;$start<=$end;$start++) {
$answer=$start;
$number=$answer;
$check="text";
$num=$answer;
if($number%2==0) {
$check="Even";
} else {
$check="Odd";
}
{ }
echo "<tr><td>$answer</td><td>$check</td><td>
<?php ?>
</td></tr>";
} echo "</table>";
} ?>
答案 0 :(得分:1)
您错过了整个主要检查,您甚至没有在第三栏中打印任何内容。
也有人似乎在第一次编辑中删除了您的代码,并在第二次编辑中更改了它。我以某种方式获得了第一个编辑的副本,可以作一个例子。
这是您代码中的一个工作示例:
<?php
$x="num1"; $y="num2";
if(isset($_POST['Submit']))
{
$start=$_POST['num1']; $end=$_POST['num2'];
echo "<table width='250' cellpadding='2' cellspacing='4' border='1'>";
echo "<tr><td>Number</td><td>Odd or Even?</td><td>Prime?</td></tr>";
for ($start;$start<=$end;$start++)
{
$answer=$start; $number=$answer; $check="text"; $num=$answer;
if($number%2==0)
{ $check="Even"; }
else
{ $check="Odd"; }
$prime = (isPrime($number)? 'Yes':'No');
echo "<tr><td>$answer</td><td>$check</td><td>$prime</td></tr>";
}
echo "</table>";
}
function isPrime($num) {
//1 is not prime. See: http://en.wikipedia.org/wiki/Prime_number#Primality_of_one
if($num == 1)
return false;
//2 is prime (the only even number that is prime)
if($num == 2)
return true;
/**
* if the number is divisible by two, then it's not prime and it's no longer
* needed to check other even numbers
*/
if($num % 2 == 0) {
return false;
}
/**
* Checks the odd numbers. If any of them is a factor, then it returns false.
* The sqrt can be an aproximation, hence just for the sake of
* security, one rounds it to the next highest integer value.
*/
for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) {
if($num % $i == 0)
return false;
}
return true;
}
?>
答案 1 :(得分:1)
试试这个
<?php
$x="num1";
$y="num2";
if(isset($_POST['Submit'])) {
$start=$_POST['num1'];
$end=$_POST['num2'];
echo "<table width='250' cellpadding='2' cellspacing='4' border='1'>";
echo "<tr><td>Number</td><td>Odd or Even?</td><td>Prime?</td></tr>";
for ($start;$start<=$end;$start++) {
$answer=$start;
$number=$answer;
$check="text";
$num=$answer;
if($number%2==0)
{
$check="Even";
}
else
{
$check="Odd";
}
if(isPrimeNumber($number))
{
$pirme_status = "Yes";
}
else
{
$pirme_status = "No";
}
echo "<tr><td>$answer</td><td>$check</td><td>$pirme_status</td><</tr>";
} echo "</table>";
}
和PHP函数是
function isPrimeNumber($number)
{
$flag = true;
$max_count = ceil($number/2);
for($i=2; $i<$max_count; $i++)
{
if($number%$i==0)
{
$flag = false;
break;
}
}
return $flag;
}
?>