liveBook · Manning

Prime number

As explained in Regular Expression Puzzles and AI Coding Assistants

A prime number is a natural number greater than one that has no positive divisors other than one and itself.

A prime number is a natural number greater than one with no positive divisors besides one and itself. The sequence begins 2, 3, 5, 7, and 11. section 5.16

The Sieve of Eratosthenes finds primes by striking out multiples of each discovered prime. A compact lazy Python version tests each candidate against the primes already found. section 5.16

When counting marks becomes arithmetic

Encode each number with that many contiguous @ symbols. Thus primes4 represents 2, 3, 5, and 7; primes5 extends the prefix with 11. By contrast, fail1 skips 5, while fail2 includes 4. The puzzle asks whether regular expressions can recognize every valid ascending initial prefix of the prime sequence. section 5.16

This is a useful trap for confident pattern matching. Lookahead assertions may resemble the sieve, but resemblance is not an implementation. The proposed regular expression does not reliably express primality; its explanation also confuses positive and negative lookahead and may match only limited arrangements of @ symbols. section 5.16 section 5.18

def get_primes():
   "Simple lazy Sieve of Eratosthenes"
   candidate = 2
   found = []
   while True:
       if all(candidate % prime != 0 for prime in found):
           yield candidate
           found.append(candidate)
       candidate += 1

Inspect the lazy Sieve implementation to compare explicit divisibility testing with the much less trustworthy regex candidate. section 5.16

How Regular Expression Puzzles and AI Coding Assistants covers it

How deep it goes
Contrasts prime definition, sieve mechanics, encoded examples, and regex failure without developing a formal impossibility proof.
Examples
Uses @-encoded prefixes such as 2 3 5 7 11 and counterexamples that skip 5 or include 4.
What it assumes
Assumes basic regular-expression notation and lookahead assertions while supplying the prime encoding and sieve comparison.
What you can do after
Evaluate prime-recognition solutions by checking correctness, edge cases, algorithmic fit, and explanations instead of trusting executable-looking code.
How it connects
Connects prime numbers with divisibility, the Sieve of Eratosthenes, regular expressions, lookahead assertions, and lazy evaluation.

Also explained in

Compare how 5 books explain prime number →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Regular Expression Puzzles and AI Coding Assistants. The section links point to the parts of the book it draws on.