Monday, June 10, 2013

Prime number program

Question: We have to ask user to enter number he/she wants, and give output whether its prime number or not?

Answer: Copy the below code and paste it into "your.php" file. After done this you will just need to run "your.php" file in browser and you will get the output successfully.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Prime number</title>
    </head>

    <body>
        <h1><center>Prime number</center></h1>

        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
            Enter number:
            <input type="text" name="num" />
            <input type="submit" name="submit" value="OK" />
        </form>

        <?php
        if (isset($_POST['submit'])) {
            $num = $_POST['num'];
            if ($num == 0) {
                echo $num . " is special number";
            } elseif ($num == 1) {
                echo $num . " is special number";
            } else {
                $c = 0;
                for ($i = 2; $i < $num; $i++) {
                    if ($num % $i == 0) {
                        $c++;
                        break;
                    }
                }
                if ($c) {
                    echo $num . " is not prime number";
                }
                else
                    echo $num . " is prime number";
            }
        }
        ?>
    </body>
</html>

No comments:

Post a Comment