pyprimes.html

download raw

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <title>Python (PyScript+MicroPython) Primes Maker</title>
        <link rel="stylesheet" href="https://pyscript.net/releases/2026.3.1/core.css" />
        <script type="module" src="https://pyscript.net/releases/2026.3.1/core.js"></script>
        <style>
        #numbers div { display: inline; }
        </style>
    </head>
    <body>
    <div id="numbers"></div>
    <button id="button">Make more...</button>
    <script type="mpy">
# Source - https://stackoverflow.com/a/568618
# Posted by Eli Bendersky, modified by community. See post 'Timeline' for change history
# Retrieved 2026-04-09, License - CC BY-SA 4.0

# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/

def gen_primes():
    """ Generate an infinite sequence of prime numbers.
    """
    # Maps composites to primes witnessing their compositeness.
    # This is memory efficient, as the sieve is not "run forward"
    # indefinitely, but only as long as required by the current
    # number being tested.
    #
    D = {}

    # The running integer that's checked for primeness
    q = 2

    while True:
        if q not in D:
            # q is a new prime.
            # Yield it and mark its first multiple that isn't
            # already marked in previous iterations
            # 
            yield q
            D[q * q] = [q]
        else:
            # q is composite. D[q] is the list of primes that
            # divide it. Since we've reached q, we no longer
            # need it in the map, but we'll mark the next 
            # multiples of its witnesses to prepare for larger
            # numbers
            # 
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]
        q += 1

def take(g, n):
    return [next(g) for _ in range(n)]

N = 1000
from pyscript import display, when
primes = gen_primes()
display(", ".join("%s" % p for p in take(primes, N)), target="#numbers")

@when("click", "#button")
def more_primes():
    display(", " + (", ".join("%s" % p for p in take(primes, N))), target="#numbers")
    </script>
    </body>
</html>