0

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..

Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

2 Answers2

4

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
        }
    }
Russell
  • 5,436
  • 2
  • 19
  • 27
  • 1
    And it should end at the `Int(sqrt(number))`. – rmaddy Feb 07 '17 at 16:59
  • 1
    It also is kind of backwards - for a non-prime it will loop more than necessary. The looping/flags should be refactored to improved efficiency asking if 10000 is Prime will loop 10000 times as is, and 10000-2=9998 times if started at 2 or 100 times with @rmaddy correction. If flagged properly, it would loop 1 time. –  Feb 07 '17 at 17:03
3
  • 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.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Doesn't the algorithm work if you put a break in the first if ? – GoodSp33d Feb 07 '17 at 17:02
  • Looks like homework - they might have been told to follow this approach. A coding exercise may have different objectives than optimising runtime performance – Russell Feb 07 '17 at 17:16