Tuesday, June 11, 2013

Find Prime numbers between given range

Question: We have to ask user to enter number1 and number2 he/she wants, and find the prime numbers between that range which is entered by users?

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>Find Prime numbers</title>
    </head>

    <body>
        <h1><center>Find Prime numbers</center></h1>

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

        <?php
        if (isset($_POST['submit'])) {
            $min = $_POST['min'];
            $max = $_POST['max'];
            if ($min == $max) {
                echo "Enter different value ";
            } else {
                if ($min > $max) {
                    $t = $min;
                    $min = $max;
                    $max = $t;
                }

                function get_prime($min, $max) {
                    $primes = array();
                    for ($x = $min; $x <= $max; $x++) {
                        if ($x == 2) {
                            $primes[] = $x;
                        }
                        for ($i = 2; $i < $x; $i++) {
                            $r = $x % $i;
                            if ($r == 0) {
                                break;
                            }
                            if ($i == $x - 1) {
                                $primes[] = $x;
                            }
                        }
                    }
                    if ($primes == NULL) {
                        echo "No prime numbers found";
                    }  else {
                        echo "Total ". count($primes) ." prime numbers:";
                        echo implode(",", $primes);
                    }
                    
                }

                get_prime($min, $max);
            }
        }
        ?>

    </body>
</html>

No comments:

Post a Comment