Evgeniy Kleban
Evgeniy Kleban

Reputation: 6965

Understanding swift functions

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

Answers (2)

Russell
Russell

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

vadian
vadian

Reputation: 285240

  • The remainder operator (%) performs a division
  • The first index is 0
  • number % divior does 10 / 0

Division 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

Related Questions