简体   繁体   English

如何使用输入检查PHP中的素数

[英]How to check prime number in PHP with an input

I need help for my php program to find a prime number. 我需要我的php程序的帮助才能找到素数。 This is my code: 这是我的代码:

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

The question is, how to check if we enter the initial value of the input to find prime numbers? 问题是, 如何检查我们是否输入输入的初始值以找到素数? If prime then the number will be red, and if it not prime will be black. 如果是素数,则数字将为红色,如果不是素数,则数字将为黑色。

I need the code to make it, any response would be greatly appreciated. 我需要编写代码,任何回应将不胜感激。

Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM