Skip to content

Instantly share code, notes, and snippets.

@iluxonchik
Created September 9, 2016 14:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iluxonchik/72e8e090fdad0c6468cba5584a7da5fe to your computer and use it in GitHub Desktop.
Save iluxonchik/72e8e090fdad0c6468cba5584a7da5fe to your computer and use it in GitHub Desktop.
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