Reputation: 6965
I'm studying swift and I wonder why following code:
func isNumberDivisible(_ number: Int, by divior: Int) -> Bool {
if number % divior == 0 {
return true;
} else {
return false;
}
}
func isPrime (_ number: Int) -> Bool {
var isPrimeNumber = false
for index in 0..<number {
if (isNumberDivisible(number, by:index )) {
isPrimeNumber = false
} else {
isPrimeNumber = true
}
}
return isPrimeNumber
}
isPrime(10)
Output an error - Execution was interrupted, EXC_BAD_INSTRUCTION..
Upvotes: -1
Views: 108
Reputation: 5554
Your for loop
starts with zero. That's a meaningless test, and so is checking if you can divide by 1.
You should start your index at 2
for index in 2..<number {
and once you find it is NOT a prime number, you should stop - what this function actually prints out is whether or not the number is divisible by (number - 1). And as @rmaddy points out, you don't need to check every number - in your example 10 is divisible by 2 and 5 - but you don't need to check 5, because you will have already failed on 2
for index in 2..<Int(sqrt(Double(number))) {
if (isNumberDivisible(number, by:index )){
isPrimeNumber = false
break
} else{
isPrimeNumber = true
}
}
Upvotes: 3
Reputation: 285240
%
) performs a divisionnumber % divior
does 10 / 0Division by zero causes a runtime error.
By the way, the first prime number is 2
for index in 2..<number
and your algorithm doesn't work anyway.
Upvotes: 2