Programming with JavaScript

⌘K
  1. Home
  2. Docs
  3. Programming with JavaScri...
  4. Practice Programs
  5. Number is prime or not in alert box

Number is prime or not in alert box

Example: 2A

Write a JavaScript to display whether a number is prime or not in alert box

Script

<html>
    <head>
        <title>PRIME NUMBER CHECKER</title>
    </head>
    <body>
        <script type = "text/javascript">
            var num = prompt("Type number here");
            num = parseInt(num);
            var b;
            var flag = 1;
            if(num <= 1)
            {
                flag = 0;
            }
            else
            {
                for(i=2;i<num;i++)
                {
                    b = num % i;
                    if(b == 0)
                    {
                        flag = 0;
                        break;
                    }
                }
            }
            if(flag == 0)
                    alert(num+"  is not a prime number");
                else
                    alert(num+"  is a prime number");
        </script>
    </body>
</html>

Output

Loading

Views: 11

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments