Home >>Javascript Programs >JavaScript code to check whether a Number is Prime or Not
In this tutorial we will understand how to check a number is prime or not by using javascript.
A prime number is a natural number can be divided by 1 and that has no positive divisors other than 1 and itself.
Let's take an example:
<html> <head> <script> function Prime() { var i,flag=0,number; number = Number(document.getElementById("N").value); for(i=2; i <= number/2; i++) { if(number%i == 0) { flag = 1; break; } } if(flag == 0) { window.alert("prime number"); } else { window.alert("not a Prime number"); } } </script> </head> <body> <br> <h1>Check Whether a number is Prime or not</h1> Enter Number :<input type="text" name="n" id = "N"/> <button onClick="Prime()">submit</button> </body> </html>
Enter Number :