Get the latest tech news

Demystifying the regular expression that checks if a number is prime (2016)


Ever wondered how the ^.?$|^(..+?)\1+$ regular expression can tell you if a number is not prime? In this blog post you'll learn how and why it works. Code examples in Java, JavaScript, Python and Perl are provided.

The explanation will be programming language agnostic, I will, however, provide Python, JavaScript and Perl versions of the Java code above and explain why they are slightly different. The lie has to do with the order in which the regex engine checks for multiples, it actually starts with the highest number and goes to the lowest, and not how I explain it here. If you remember correctly, I said that due to the peculiarities of the way String.matches works in Java, the regular expression that matches non-prime numbers is not the one in the code example above (.?|(..+?

Get the Android app

Or read this on Hacker News

Read more on:

Photo of number

number

Photo of regular expression

regular expression

Related news:

News photo

Linux Working On A Counter To Keep Track Of The Number Of Hung Tasks Since Boot

News photo

47 percent of UK Nintendo Switch players are women | Study shows number of female Switch players has nearly doubled in five years.

News photo

India Is Now Russia’s Number Two Supplier of Restricted Technology