The idea came from this video: https://www.youtube.com/watch?v=5vbk0TwkokM
He refers also to this very detailed explanation: https://illya.sh/the-codeumentary-blog/r...-is-prime/
The regex
As representation, the digit
Example Code with 🎃 as symbol.
He refers also to this very detailed explanation: https://illya.sh/the-codeumentary-blog/r...-is-prime/
The regex
^.?$|^(..+?)\1+$
returns False
if the digit is a prime.As representation, the digit
1
is used, but any symbol could be used.Example Code with 🎃 as symbol.
import re from itertools import count # Python 3.13.0 compatible, not tested without gil (3.13.0t) import sympy # to make it very clear, it can by any unicode character with the len 1 SYMBOL = "🎃" if len(SYMBOL) != 1: raise RuntimeError(f"Symbol {SMYBOL} is not length == 1") def is_prime(value: int) -> bool: """ Video: https://www.youtube.com/watch?v=5vbk0TwkokM Link to the blog post: https://illya.sh/the-codeumentary-blog/regular-expression-check-if-number-is-prime/ """ return not re.match(r"^.?$|^(..+?)\1+$", SYMBOL * value) def first_100_primes() -> list[int]: primes = [] for n in count(2): if len(primes) >= 100: return primes if is_prime(n): primes.append(n) primes = first_100_primes() # safety check for prime in primes: if not sympy.isprime(prime): raise ValueError(f"The number {prime} is not a prime") for index in range(0, len(primes) + 1, 10): if chunk := primes[index : index + 10]: for prime in chunk: print(f"{prime:>3}", end=" ") print()
Output: 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 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
PS: As he explains in the Video, the order of the operation of the regex matching algorithm depends on the implementation. There is internally heavy optimization going on, which leads into different execution of the recursive matching. This code should not be used to check prime numbers.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!