【问题标题】:How to check prime number in PHP with an input如何使用输入检查 PHP 中的素数
【发布时间】:2014-04-22 11:43:06
【问题描述】:

我需要帮助我的 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>

问题是,如何检查我们是否输入了输入的初始值来查找素数?如果是素数,则数字将为红色,如果不是素数,则为黑色。

我需要代码来制作它,任何回复将不胜感激。

【问题讨论】:

标签: php for-loop html-table numbers


【解决方案1】:

试试:

<?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;
?>

【讨论】:

    猜你喜欢
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 2016-07-07
    • 2012-09-30
    相关资源
    最近更新 更多