Prime Number in Swift

Published on 10 March 2026 (Updated: 10 March 2026)

Welcome to the Prime Number in Swift page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

import Foundation

let usage = "Usage: please input a non-negative integer"

if CommandLine.arguments.count != 2 {
    print(usage)
    exit(0)
}

guard let number = Int(CommandLine.arguments[1]), number >= 0 else {
    print(usage)
    exit(0)
}

if number < 2 {
    print("composite")
    exit(0)
}

var isPrime = true
let limit = Int(Double(number).squareRoot())

if limit >= 2 {
    for i in 2...limit {
        if number % i == 0 {
            isPrime = false
            break
        }
    }
}

print(isPrime ? "prime" : "composite")

Prime Number in Swift was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.