JavaScript - program to display n prime numbers using javascript

Asked By hari on 22-Oct-10 04:33 AM
program to print n prime no's using javascript
Jatin Prajapati replied to hari on 22-Oct-10 05:00 AM
var val=""
var count=0
function prime()
{
   var i = 1
   while(count<=1000)
   {
   var isPrime=1
   for (j=2; j<=Math.sqrt(i); j++)
   {
   if(i%j==0) 
   {
   isPrime=0
   }
   }
   count=(isPrime==1?count+1:count)
   if (isPrime==1)
   {
  val=val+"<br>"+i
   }
   i=i+1
  }
  document.write(val)
}

Reena Jain replied to hari on 22-Oct-10 05:05 AM
hi,

here is the code for this
var primes = new Array;
primes.push(2);// special - only even prime
for (var i = 3; i < 1000; i += 2)
{
  var iSqrt = Math.floor(Math.sqrt(i));
  var bPrime = true;
  for ( j = 0; primes[j] <= iSqrt; j++ )
  {
    if ( i % primes[j] == 0 )
    {
      bPrime = false;
      break;
    }
  }
  if ( bPrime ) primes.push(i);
}
document.write(primes.join());

Hope this will help you