Skip to content

Instantly share code, notes, and snippets.

@mredig
Last active June 12, 2019 15:36
Show Gist options
  • Save mredig/4042fb9da4d48c4b6ba89b8551edcb79 to your computer and use it in GitHub Desktop.
Save mredig/4042fb9da4d48c4b6ba89b8551edcb79 to your computer and use it in GitHub Desktop.
checks to see if a number is a twin prime
// a twin prime is where a prime number +/- 2 is another prime number. For example, 3 is prime, and so is 5. They are twin primes. (Since 7 is 2 away from 5 as well, maybe that makes them triplets! But I'm not a mathematician. I'll let them decide.)
extension FixedWidthInteger {
func isPrime() -> Bool {
// negatives, 0, and 1 are all not prime and will break the range created below
guard self >= 2 else { return false }
// no even numbers are prime, except 2
guard !self.isMultiple(of: 2) else {
return self == 2 ? true : false
}
// ANY value above n / 2 is NEVER going to divide into n evenly. +1 is simply for the edge case of 3 (3/2 = 1 (Int, btw) and then trying to do a range of 2..<1 crashes)
let max = self / 2 + 1
// only need to compare against odd numbers - even numbers were eliminated in the second guard
for divisor in 2..<max where !divisor.isMultiple(of: 2) {
// if a number is divisible by anything other and itself and 1, it's not prime
if self.isMultiple(of: divisor) {
return false
}
}
// exhausted all possibilities that could make self not prime
return true
}
func isTwinPrime() -> Bool {
// if self isn't prime, it definitely isnt a twin prime
guard self.isPrime() else { return false }
// but if it is, check to see if self - 2 is
if (self - 2).isPrime() {
return true
} else if (self + 2).isPrime() { // maybe self + 2 is?!
return true
} else { // oh well, we tried
return false
}
}
}
0.isPrime()
1.isPrime()
2.isPrime()
3.isPrime()
4.isPrime()
5.isPrime()
for testNum in 0...10000 {
if testNum.isTwinPrime() {
print(testNum)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment