dimanche 20 septembre 2015

How to generate 100 random numbers and checking each one for primality?

Write a Boolean function named isPrime which takes an integer as an argument and returns true if the argument is a prime number of false otherwise. Generate 100 random numbers and display the results of checking each one for primality.

This is supposed to output the random numbers that are prime (after the true or false check) but I am getting the results of 2 sets of numbers in order.

Here is my code:

    var arr = []
    while(arr.length < 100){
      var randomnumber=Math.ceil(Math.random()*100)
      var found=false;


      for(var i=0;i<arr.length;i++){
        if(arr[i]==randomnumber){found=true;break}
      }
      if(!found)arr[arr.length]=randomnumber;
    }
    console.log(arr);
    for(i = 0; i < 100; i++){
        if(isPrime(i)) console.log(i);
    }

    function isPrime(num) {
        if(num < 2) return false;
        for (var i = 2; i < num; i++) {
            if(num%i==0)
                return false;
        }
        return true;
    }




Aucun commentaire:

Enregistrer un commentaire