isPrime() Javascript represents a prime number checker function in Javascript.
Prime number is a number which is divisible by one and number itself.
like numbers 5,7,11,13,17, etc are prime numbers.
Prime number program in javascript using for loop
Below program uses for loop to check a number is prime or not.
Create a function isPrime() to check the number is prime or not.
- get the number
- check a number is divisible by 2 to num/2
- if divisible then not a prime number
- else it is a prime number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <!DOCTYPE html> <html> <head> <title>Prime Number Checker</title> <script > function isPrime() { var num = document.getElementById("num").value; var count = 0; for (i = 2; i <= num / 2; i++) { check = num % i; if (check == 0) { count++; break; } } if (count > 0) { document.getElementById("result").innerHTML = num + " not a prime number"; } else { document.getElementById("result").innerHTML = num + " is a Prime number"; } } </script> </head> <body> <h2> Prime Number Checker </h2> <p> Enter a number to check is it prime or not </p> <label> Enter a Number </label> <input type = "number" id = "num" /> <input type = "button" value = "Check Prime" onclick = "isPrime()" /> <br/> <p id = "result"></p> </body> </html> |
In above program we have create isPrime() Javascript function.
Function is checking whether a number is prime or not.
To get text box value document.getElementById("num").value
is used here document represents the html page and method getElementById is accepting a html elements id.
based on it is finding its value.
To show result in paragraph element with id result document.getElementById("result").innerHTML
is used.