In this post, we are going to see how to print Prime numbers between two intervals in JavaScript. This program also helps you to understand basic concepts in JavaScript such as how to get value from a form input, print in a div tag, how to loop in JavaScript and call a function, etc.,
Here is the entire script for you,
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 34 35 36 37 38 39 40 41 42 43 44 45 |
<html> <head> <title>JavaScript to print prime numbers between two integers!</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> function printPrime() { "use strict"; var i, j, c, start, end; //get the start and end value from form start = parseInt(document.getElementById('start').value); end = parseInt(document.getElementById('end').value); //clear the result div document.getElementById("result").innerHTML = ''; //loop till i equals to end for (i = start; i <= end; i++) { c = 0; for (j = 1; j <= i; j++) { // % modules will give the reminder value, so if the reminder is 0 then it is divisible if (i % j == 0) { //increment the value of c c++; } } //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").insertAdjacentHTML('beforeend', i + '<br>'); } } } </script> </head> <body> <h2>JavaScript to print Prime numbers between two integers!</h2> Start: <input type="number" name="start" id="start" min="1" style="width: 100px;" value="10" /> End: <input type="number" name="end" id="end" min="1" style="width: 100px;" value="100" /> <input type="submit" value="Print Prime Numbers" onclick="printPrime()" name="print" /> <div id="result"></div> </body> </html> |
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers from 1 to 12 are 2, 3, 5, 7, 11.
You can even check the demo of the script in here:
Enjoy. Have a nice day!