Skip to content

Instantly share code, notes, and snippets.

@AustinBCole
Last active December 5, 2018 21:04
Show Gist options
  • Save AustinBCole/6e7bdc372c8129eb96fb4b02872bdda3 to your computer and use it in GitHub Desktop.
Save AustinBCole/6e7bdc372c8129eb96fb4b02872bdda3 to your computer and use it in GitHub Desktop.
Assumptions:
I do not have any assumptions, it seems pretty straightforward.
Test Cases:
1. 0
2. 4
3. 33
4. 24
5. 9
6. 2
7. 7
Implementation:
I will create an array of Int containing [2, 3, 4, 5, 6, 7, 8, 9]. I will write an if statement checking to see if the integer
passed into the function is greater than 10. If so, I will use modulo to see if the integer passed is divisible by any numbers
in the array. If true, the number is a prime number. I will then do the same check for two numbers after and two numbers before.
If none of them are divisble the function will return true.
I will then enter all the numbers before 10 manually and use a switch statement indicating whether or not they fit the
criteria.
Code:
func isTwinPrime(number: Int) -> Bool {
var myBool: Bool = false
let divisibleArray: [Int] = [2, 3, 4, 5, 6, 7, 8, 9]
if number >= 10 {
let newArray = divisibleArray.filter { (index) -> Bool in
number % index == 0
}
myBool = newArray.count > 0 ? false : true
if myBool == true {
let newArray = divisibleArray.filter { (index) -> Bool in
(number + 2) % index == 0
}
myBool = newArray.count > 0 ? false : true
if myBool == true {
let newArray = divisibleArray.filter { (index) -> Bool in
(number - 2) % index == 0
}
myBool = newArray.count > 0 ? false : true
}
}
} else {
switch number {
case 1:
myBool = true
case 3:
myBool = true
case 5:
myBool = true
default:
myBool = false
}
}
return myBool
}
isTwinPrime(number: 5)
I edited this code after 9:45. However, I edited it because I suddenly thought that I had misunderstood the instructions. However, I returned it back to how it was. Thanks.
@dillon-mce
Copy link

This should work, with a few small changes. You need a case for 7 in your switch, because that should return true and it is less than 10. You also want to have line 40 be if myBool != true or if myBool == false or if !myBool because right now it'll only run if the number 2 higher that the number is a prime, but if that is the case you should have already returned true (you only need one of them to be a prime). If you make those two changes you'll have a mostly working function.

The only remaining issue is factors bigger than the ones you've listed in your array, for instance 13. If you run isTwinPrime(169) you should get false because it is divisible by 13. But (assuming you've made the changes I listed above) you'll see that it returns true. This is because it isn't divisible by anything in your array and 167 is a prime number. So you'd want to account for bigger divisors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment