Hello friends,
Today’s post is about how to print a series of Prime numbers using only JavaScript. This script could help you to understand the basic concepts of JavaScript.
So basically the entire script is here. Just go through and ask me doubts in the comments section if you have any!
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 |
<html> <head> <title>JavaScript to print prime numbers!</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> function printPrime() { var i = 0; var j = 0; limit = document.getElementById('limit').value; //loop till i equals to $limit for (i = 1; i <= limit; 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!</h2> Enter the limit: <input type="number" name="limit" id="limit" min="0" style="width: 100px;" /> <input type="submit" value="Print Prime Numbers" onclick="printPrime()" name="print" /> <div id="result"></div> </body> </html> |
If you don’t know what is a prime number. Let me explain it:
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!
Can we have iteraction with Explanation Also.Thanks!!!