[javascript] How to find prime numbers between 0 - 100?

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

_x000D_
_x000D_
// 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(', ')
_x000D_
<dl>
<dt>Primes under 100</dt>
<dd></dd>
</dl>
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to math

How to do perspective fixing? How to pad a string with leading zeros in Python 3 How can I use "e" (Euler's number) and power operation in python 2.7 numpy max vs amax vs maximum Efficiently getting all divisors of a given number Using atan2 to find angle between two vectors How to calculate percentage when old value is ZERO Finding square root without using sqrt function? Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt? How do I get the total number of unique pairs of a set in the database?

Examples related to primes

Python Prime number checker Check if number is prime number Python Finding Prime Factors isPrime Function for Python Language How to find prime numbers between 0 - 100? Print series of prime numbers in python Calculating and printing the nth prime number Why do we check up to the square root of a prime number to determine if it is prime? Printing prime numbers from 1 through 100 Determining if a number is prime