Running sieve.js

➕︎ Aa ➖︎ |Dark 1Dark 2Light|HackFira Code|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 n_sqrt = Math.floor(Math.sqrt(n));
   
   for (var p=2; p<=n; p++)
      a[p] = p;
      
   for (p=2; p<=n_sqrt; p++)
      if ( a[p] != 0 )
         for (var 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];
}