Create a gist now

Instantly share code, notes, and snippets.

Regex that checks if a number is prime in Swift 2. From blog post "Demystifying The Regular Expression That Checks If A Number Is Prime" at https://iluxonchik.github.io/regular-expression-check-if-number-is-prime/ | Submitted by Russel: https://disqus.com/by/disqus_527bF1C8Ck/
/*
Regex that checks if a number is prime in Swift 2.
From blog post "Demystifying The Regular Expression That Checks If A Number Is Prime"
at https://iluxonchik.github.io/regular-expression-check-if-number-is-prime/
Submitted by Russel: https://disqus.com/by/disqus_527bF1C8Ck/
*/
func isPrime(n: Int) -> Bool {
do {
return try NSRegularExpression(
pattern: "^.?$|^(..+?)\\1+$",
options: []).matchesInString(
String(count: n, repeatedValue: Character("1")),
options: [],
range: NSMakeRange(0, n)
).count == 0
} catch {
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment