Running sieve.js

➕︎ Aa ➖︎ |Dark 1Dark 2Light|HackInput Mono|Back to  PT Mono
// CPCS 223 Analysis & Design of Algorithms
// Section 1.1 What is an Algorithm - sieve
// 2020, Dr. Muhammad Al-Hashimi

var ell = [], limit=100;
sieve(limit);

document.write("<p>Prime numbers up to ", limit, "</p>");
document.write("<p>", ell, "</p>");

// note tags <p></p> to enclose output in a paragraph

function sieve(n)
{
   var a = [];
   var sqrt_n = Math.floor(Math.sqrt(n));
   
   for (var p=2; p<=n; p++)
      a[p] = p;
      
   for (p=2; p<=sqrt_n; p++)
      if ( a[p] != 0 )
         for (j=p*p; j<=n; j += p)
            a[j] = 0;
      
   var i = 0
   for (p=2; p<=n; p++)
      if ( a[p] != 0 ) 
         ell[i++] = a[p];
}