简体   繁体   中英

How to check prime number in PHP with an input

I need help for my php program to find a prime number. 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;
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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