Swift Program – Check Prime Number

Print Even Numbers

To check if a given number is prime or not, we shall implement the following conditions in the function isPrime() that checks if the number is prime or not.

  • If number is not greater than or equal to 2, the number is not a valid prime.
  • If the number is 2, the number is prime.
  • If the number is divisible by 2, the number is not prime.
  • From number 3, in steps (strides) of 2, until the square root of given number, if none of the stride satisfies the condition that n leaves no reminder when divided with each stride, then the number is prime.

In the following program, we will build the function isPrime() that accepts an integer, and implements the above said conditions.

main.swift

import Foundation

func isPrime(_ n: Int) -> Bool {
    guard n >= 2     else { return false }
    guard n != 2     else { return true  }
    guard n % 2 != 0 else { return false }
    return !stride(from: 3, through: Int(sqrt(Double(n))), by: 2).contains { n % $0 == 0 }
}

print("Is 9 prime? \(isPrime(9))")
print("Is 11 prime? \(isPrime(11))")
print("Is 123 prime? \(isPrime(123))")

Program Output

Is 9 prime? false
Is 11 prime? true
Is 123 prime? false

Summary

Summarising this tutorial, we learned how to check if a given number is prime or not.