JavaScript Program to Check Prime Number Example


Share:
 | Published By: Admin | Published On: Nov 01, 2021 | Category: Javascript


Hello Friends,

Now let's see example of how to check prime number example. We will use how to check prime number in javascript. This is a short guide on check prime number. Let's get started with how to check prime number in javascript.

Here i will give you many example how you can check prime number javascript.

Example : 1
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>JavaScript Program to Check Prime Number Example - MyWebtuts.com</title>
    </head>
    <body>
        <h2>JavaScript Program to Check Prime Number Example - MyWebtuts.com</h2>
        
        <script type="text/javascript">
            const num = parseInt(prompt("Enter a positive Number: "));
            let isPrime = true;

            if (num === 1) {
                document.write("1 is neither Prime nor composite Number.");
            }

            else if (num > 1) {
                for (let i = 2; i < num; i++) {
                    if (num % i == 0) {
                        isPrime = false;
                        break;
                    }
                }

                if (isPrime) {
                    document.write(`${num} is a Prime Number`);
                } else {
                    document.write(`${num} is not a Prime Number`);
                }
            }

            else {
                document.write("The Number is not a Prime Number.");
            }
        </script>
    </body>
</html>
Output : Example : 2
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>JavaScript Program to Check Prime Number Example - MyWebtuts.com</title>
    </head>
    <body>
        <h3>JavaScript Program to Check Prime Number Example - MyWebtuts.com</h3>
        <form name="myform">
            Enter the number:
            <input type="text" name=n value="">
            <br><br>
            
            <input type="button" value="Check" onClick="test()">
            <br>
        </form>
        <script type="text/javascript">
            function test() {
                var n, i, flag = true;
                
                n = document.myform.n.value;
                n = parseInt(n)
                for(i = 2; i <= n - 1; i++)
                    if (n % i == 0) {
                        flag = false;
                        break;
                    }
                    if (flag == true)
                        alert(n + " is Prime Number");
                    else
                        alert(n + " is not Prime Number");
                }
        </script>
    </body>
</html>
Output :

It will help you...

Share: