JavaScript Prime Number

1.5k Views Asked by At

In JavaScript, how would I generate 100 random numbers and display the results of checking each one for primality, if I'm using a Boolean function named isPrime which then takes an integer as an argument and returns true if the argument is a prime number of false? For some reason I am stuck..

So far I have this:

function isPrime(number) {
    var start = 2;
    while (start <= Math.sqrt(number)) {
        if (number % start++ < 1) return false;
    }
    return number > 1;
}
2

There are 2 best solutions below

0
On

how would I generate 100 random numbers

Use the Math.random() function. I assume you want random integers in some interval, so you can use a function like this:

function randomList(n, min, max) {
  var list = [];
  for(var i = 0; i < n; i++) {
    list.push(Math.floor(min + Math.random() * (max - min)));
  }
  return list;
}

To generate, say, 100 random numbers between 0 and 250, you could call

randomList(100, 0, 250)

and display the results of checking each one for primality

Loop through the random numbers you generated and use your isPrime function to check each one for primality:

var list = randomList(100, 0, 250);
for(var i = 0; i < list.length; i++) {
  var num = list[i];
  console.log(num + (isPrime(num) ? " is prime." : " is not prime."));
}
0
On

you want to generate a random number use:

 Math.random();

this only gives you a number like 0.8656630991026759 now what is the limit of your random number? 0 to 100 or some other limits so you can simply multiply this number with higher limit.

for example Math.random()*100 should give me a random number from 0 to 100.

now check if the number is prime. Here are two examples of isprime:

// This version has the fewest lines of code - but is very slow.
// It checks if n is dividible by every integer 2, 3, 4, 5 ... 
// up to sqrt(n)

function isPrime1(n) {
 if (isNaN(n) || !isFinite(n) || n%1 || n<2) return false; 
 var m=Math.sqrt(n);
 for (var i=2;i<=m;i++) if (n%i==0) return false;
 return true;
}

// The next version is better: it checks the divisor 2 separately;
// then, it proceeds to check odd divisors only, from 3 up to sqrt(n).
// At most half of the numbers between 3 and sqrt(n) are checked.

function isPrime2(n) {
 if (isNaN(n) || !isFinite(n) || n%1 || n<2) return false; 
 if (n%2==0) return (n==2);
 var m=Math.sqrt(n);
 for (var i=3;i<=m;i+=2) {
  if (n%i==0) return false;
 }
 return true;
} 

check this link for more info on isprime function source : http://www.javascripter.net/faq/numberisprime.htm