我的php程序需要帮助才能找到素数。这是我的代码:
<form method="post" action="">
<table border="1" width="180px">
<thead>
<tr bgcolor="yellow">
<th>#</th>
<th>Data 1</th>
<th>Data 2</th>
<th>Data 3</th>
</tr>
</thead>
<?php
error_reporting(0);
$start = 21;
$n_rows = 5;
$n_cols = 4;
for ($i = 0; $i < $n_rows; $i++) {
$row = '';
for ($j = 0; $j < $n_cols; $j++) {
$row .= '<td>'. ($start + $i + ($j * $n_rows)). '</td>';
}
$out .= '<tr>'. $row. '</tr>';
}
echo $out;
?>
<tr>
<td colspan=4>
<center>
<label for="input">Initial value:</label>
<input type="text" name="awal" style="width: 60px">
<input type="submit" name="submit" value="Send">
</center>
</td>
</tr>
</table>
</form>
问题是,如何检查我们是否输入输入的初始值来查找素数?如果是素数则数字将为红色,如果不是素数将为黑色。
我需要代码来制作它,任何回复都会非常感激。
答案 0 :(得分:0)
尝试:
<?php
error_reporting(0);
//this function will check whether the number passed to it is prime or not
function isPrime($n)
{
if ($n == 1) return false;
if ($n == 2) return true;
if ($n % 2 == 0)
{
return false;
}
$i = 2;
for ($i = 2; $i < $n; $i++)
{
if ($n % $i == 0)
{
return false;
}
}
return true;
}
//if initial value set, take that value or else begin from 1
if (isset($_POST['awal']) && $_POST['awal'] != 0)
{
$start = $_POST['awal'];
}
else
{
$start = 1;
}
$n_rows = 5;
$n_cols = 4;
for ($i = 0; $i < $n_rows; $i++)
{
$row = '';
for ($j = 0; $j < $n_cols; $j++)
{
$number = ($start + $i + ($j * $n_rows));
//checking if number prime
if (isPrime($number) == true)
{
//if prime color it red
$row.= '<td style="color:red">' . ($start + $i + ($j * $n_rows)) . '</td>';
}
else
{
$row.= '<td>' . ($start + $i + ($j * $n_rows)) . '</td>';
}
}
$out.= '<tr>' . $row . '</tr>';
}
echo $out;
?>