JavaScript – Find Prime number or not!

Hello JavaScript beginners and school / college students here is another interesting program that will help you to understand the basic concepts of JavaScript such as how to get a value from an input, How to print the value in a div etc.,

So this simple JavaScript program will tell you that the entered number is a Prime number or not!

Let’s see the program first, If you want to see the demo you can find the button at the end of this post.

<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript to find prime number or not!</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script>
            function findPrime(){
                //get the input value
                var num = document.getElementById('num').value;
                var c = 0;

                //loop till i equals to $num
                for (i = 1; i <= num; i++) {
                    //check if the $num is divisible by itself and 1
                    // % modules will give the reminder value, so if the reminder is 0 then it is divisible
                    if (num % i == 0) {
                        //increment the value of c
                        c = c + 1;
                    }
                }

                //if the value of c is 2 then it is a prime number
                //because a prime number should be exactly divisible by 2 times only (itself and 1)
                if (c == 2) {
                    document.getElementById('result').innerHTML = num + ' is a Prime number';
                }else{
                    document.getElementById('result').innerHTML = num + ' is NOT a Prime number';
                }
            }        
        </script>
    </head>
    <body>
        <h2>JavaScript to find Prime number or not!</h2>
        <form method="post">
            Enter a number:  <input type="number" id="num" name="num" min="0" /><input type="button" value="Find Prime Number" onclick="findPrime()" name="find" />
            <div style="margin-top: 10px;" id="result"></div>
        </form>
    </body>
</html>

Go through code and read the comments in the above script to understand what each and every line of the JavaScript is doing.

You can see the demo here:

demo

 

1 thought on “JavaScript – Find Prime number or not!”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top