TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

How on Earth does ^.?$|^(..+?)\1+$ produce primes? [video]

5 pointsby sandebert7 months ago

2 comments

jfengel7 months ago
The answer is &quot;by brutest possible force&quot;.<p>It does trial division on the number in base 1 representation. That is, as a string of N 1s. It takes every sub-string of the number (except 0 and 1) and sees if you can reproduce the original in an integer number of steps.<p>^(..+?) is a substring of at least 2 characters at the beginning \1 is a copy of it +$ is the part doing the work: look for an exact number of copies, filling up the entire string<p>The ^.?$ part is &quot;0 and 1 don&#x27;t count&quot;.<p>It&#x27;s basically equivalent to a for loop from 1 to N. Divide N by the number and look for a remainder. Except that the division is done in base 1, by duplicating the string over and over and seeing it it lines up.<p>Clever, but certainly not useful.
timonoko7 months ago
Regexpr is confused with &quot;+?&quot; so<p><pre><code> ^.?$|^(..*)\1+$ </code></pre> is better.