Guest User

boolean-sieve

a guest
Apr 4th, 2022
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 5 1.81 KB | None | 0 0
  1. <!--
  2. An implementation of Sieve of Eratosthenes using a boolean array
  3. Author: Nguyen Thanh Do
  4. -->
  5. <!DOCTYPE html>
  6. <html>
  7.     <head>
  8.         <title>Sieve of Eratosthenes</title>
  9.     </head>
  10.     <body>
  11.         <h3>Sieve of Eratosthenes</h3>
  12.         <input type="number" id="input-number">
  13.         <p>Click the button to submit the limit</p>
  14.         <button onclick="show()">Submit</button>
  15.         <p id="output-intro"> </p>
  16.         <p id="output-numbers"></p>
  17.     </body>
  18.     <script>
  19.         let limit;
  20.         let notPrime;
  21.         let result;
  22.         let sentence;
  23.        
  24.         function getInput() {
  25.             limit = document.getElementById("input-number").value;
  26.         }
  27.        
  28.         function markPrimes() {
  29.             notPrime = new Array(parseInt(limit) + 1).fill(false);
  30.        
  31.             notPrime[0] = notPrime[1] = true;
  32.        
  33.             for (let num = 4; num <= limit; num += 2)
  34.                 notPrime[num] = true;
  35.        
  36.             for (let num = 3; num <= Math.sqrt(limit); num +=2) {
  37.                 if (notPrime[num] === false) {
  38.                     for (let mul = num * num; mul <= limit; mul += num * 2)
  39.                         notPrime[mul] = true;
  40.                 }
  41.             }
  42.         }
  43.        
  44.         function printPrimes() {
  45.             sentence = "List of prime numbers from 1 to " + (String(limit) + ": ");
  46.             result = '';
  47.  
  48.             for (let num = 0; num <= limit; num++) {
  49.                 if (notPrime[num] === false)
  50.                     result += (String(num) + ' ');
  51.             }
  52.  
  53.             document.getElementById("output-intro").innerHTML = sentence;
  54.             document.getElementById("output-numbers").innerHTML = result;  
  55.         }
  56.  
  57.         function noPrime() {
  58.             sentence = "There is no prime number. Please enter a number greater than or equal to 2";
  59.             result = '';
  60.  
  61.             document.getElementById("output-intro").innerHTML = sentence;
  62.             document.getElementById("output-numbers").innerHTML = result;  
  63.         }
  64.        
  65.         function show() {
  66.             getInput();
  67.        
  68.             if (limit < 2) {
  69.                 noPrime();
  70.             }
  71.             else {
  72.                 markPrimes();
  73.                 printPrimes();
  74.             }
  75.         }
  76.     </script>
  77. </html>
  78.  
Advertisement
Add Comment
Please, Sign In to add comment