How to find prime numbers between 0 - 100?

Viewed 207360

In Javascript how would i find prime numbers between 0 - 100? i have thought about it, and i am not sure how to find them. i thought about doing x % x but i found the obvious problem with that. this is what i have so far: but unfortunately it is the worst code ever.

var prime = function (){
var num;
for (num = 0; num < 101; num++){
    if (num % 2 === 0){
        break;
    }
    else if (num % 3 === 0){
        break;
    }
    else if (num % 4=== 0){
        break;
    }
    else if (num % 5 === 0){
        break;
    }
    else if (num % 6 === 0){
        break;
    }
    else if (num % 7 === 0){
        break;
    }
    else if (num % 8 === 0){
        break;
    }
    else if (num % 9 === 0){
        break;
    }
    else if (num % 10 === 0){
        break;
    }
    else if (num % 11 === 0){
        break;
    }
    else if (num % 12 === 0){
        break;
    }
    else {
        return num;
    }
}
};
console.log(prime());
40 Answers
            var n=100;
            var counter = 0;
            var primeNumbers = "Prime Numbers: ";
            for(var i=2; i<=n; ++i)
            {
                counter=0;
                for(var j=2; j<=n; ++j)
                {
                    if(i>=j && i%j == 0)
                    {
                        ++counter;
                    }

                }
                if(counter == 1)
                    {
                        primeNumbers = primeNumbers + i + "  ";
                    }

            }
            console.log(primeNumbers);

Using recursion combined with the square root rule from here, checks whether a number is prime or not:

function isPrime(num){

    // An integer is prime if it is not divisible by any prime less than or equal to its square root
    var squareRoot = parseInt(Math.sqrt(num));
    var primeCountUp = function(divisor){
        if(divisor > squareRoot) {
            // got to a point where the divisor is greater than 
            // the square root, therefore it is prime
            return true;
        }
        else if(num % divisor === 0) {
            // found a result that divides evenly, NOT prime
            return false;
        }
        else {
            // keep counting
            return primeCountUp(++divisor);
        }
    };

    // start @ 2 because everything is divisible by 1
    return primeCountUp(2);

}

You can try this method also, this one is basic but easy to understand:

 var tw = 2, th = 3, fv = 5, se = 7; 

 document.write(tw + "," + th + ","+ fv + "," + se + ",");


for(var n = 0; n <= 100; n++)
{

  if((n % tw !== 0) && (n % th !==0) && (n % fv !==0 ) && (n % se !==0))

  {
      if (n == 1)
      {
          continue;
      }

    document.write(n +",");
  }
}

I recently came up with a one-line solution that accomplishes exactly this for a JS challenge on Scrimba (below).

ES6+

const getPrimes=num=>Array(num-1).fill().map((e,i)=>2+i).filter((e,i,a)=>a.slice(0,i).every(x=>e%x!==0));

< ES6

function getPrimes(num){return ",".repeat(num).slice(0,-1).split(',').map(function(e,i){return i+1}).filter(function(e){return e>1}).filter(function(x){return ",".repeat(x).slice(0,-1).split(',').map(function(f,j){return j}).filter(function(e){return e>1}).every(function(e){return x%e!==0})})};

This is the logic explained:

  1. First, the function builds an array of all numbers leading up to the desired number (in this case, 100) via the .repeat() function using the desired number (100) as the repeater argument and then mapping the array to the indexes+1 to get the range of numbers from 0 to that number (0-100). A bit of string splitting and joining magic going on here. I'm happy to explain this step further if you like.

  2. We exclude 0 and 1 from the array as they should not be tested for prime, lest they give a false positive. Neither are prime. We do this using .filter() for only numbers > 1 (≥ 2).

  3. Now, we filter our new array of all integers between 2 and the desired number (100) for only prime numbers. To filter for prime numbers only, we use some of the same magic from our first step. We use .filter() and .repeat() once again to create a new array from 2 to each value from our new array of numbers. For each value's new array, we check to see if any of the numbers ≥ 2 and < that number are factors of the number. We can do this using the .every() method paired with the modulo operator % to check if that number has any remainders when divided by any of those values between 2 and itself. If each value has remainders (x%e!==0), the condition is met for all values from 2 to that number (but not including that number, i.e.: [2,99]) and we can say that number is prime. The filter functions returns all prime numbers to the uppermost return, thereby returning the list of prime values between 2 and the passed value.

As an example, using one of these functions I've added above, returns the following:

getPrimes(100);
// => [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]

Here's the very simple way to calculate primes between a given range(1 to limit).

Simple Solution:

    public static void getAllPrimeNumbers(int limit) {

        System.out.println("Printing prime number from 1 to " + limit);

        for(int number=2; number<=limit; number++){
            //***print all prime numbers upto limit***
            if(isPrime(number)){
                System.out.println(number);
            }
        }
    }


    public static boolean isPrime(int num) {
        if (num == 0 || num == 1) {
            return false;
        }
        if (num == 2) { 
            return true;
        }

        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }

A version without any loop. Use this against any array you have. ie.,

[1,2,3...100].filter(x=>isPrime(x));
const isPrime = n => {
if(n===1){
return false;
}
if([2,3,5,7].includes(n)){
return true;
}
return n%2!=0 && n%3!=0 && n%5!=0 && n%7!=0;
}

I was searching how to find out prime number and went through above code which are too long. I found out a new easy solution for prime number and add them using filter. Kindly suggest me if there is any mistake in my code as I am a beginner.

function sumPrimes(num) {

let newNum = [];

for(let i = 2; i <= num; i++) {
newNum.push(i)
}
for(let i in newNum) {

newNum = newNum.filter(item => item == newNum[i] || item % newNum[i] !== 0)
}

return newNum.reduce((a,b) => a+b)
}

sumPrimes(10);

Here is an efficient, short solution using JS generators. JSfiddle

// Consecutive integers
let nats = function* (n) {
    while (true) yield n++
}

// Wrapper generator
let primes = function* () {
    yield* sieve(primes(), nats(2))
}

// The sieve itself; only tests primes up to sqrt(n)
let sieve = function* (pg, ng) {
    yield ng.next().value;
    let n, p = pg.next().value;
    while ((n = ng.next().value) < p * p) yield n;
    yield* sieve(pg, (function* () {
        while (n = ng.next().value) if (n % p) yield n
    })())
}

// Longest prefix of stream where some predicate holds
let take = function* (vs, fn) {
    let nx;
    while (!(nx = vs.next()).done && fn(nx.value)) yield nx.value
}

document.querySelectorAll('dd')[0].textContent =

// Primes smaller than 100
    [...take(primes(), x => x < 100)].join(', ')
<dl>
<dt>Primes under 100</dt>
<dd></dd>
</dl>

function isPrime(num) {
  for(var i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num ;
}
function primes(n){
  var array_of_primes=[];
for(var i = 2; i < n; i++){
    if(isPrime(i)) array_of_primes.push(i)>1;
     }
   return array_of_primes;
}
document.write(primes(10000));
Related