Created
September 9, 2016 14:09
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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