check if a number is prime, if it is composite print a list of factors in swift

main.swift
func checkIfNumberIsPrime(_ number: Int) -> Bool {
    guard number > 1 else { return false } // 0, 1 and negative numbers are not primes
    
    for i in 2..<number {
        if number % i == 0 {
            return false
        }
    }
    
    return true
}

func printListFactors(_ number: Int) {
    guard number > 2 else { return } // numbers below 3 have no factors
    
    for i in 2...number/2 {
        if number % i == 0 {
            print(i)
        }
    }
}
475 chars
22 lines

The checkIfNumberIsPrime function returns a boolean value that indicates if the given number is prime or not. The function checks for numbers that are less than the given number, starting from 2, and if any of them divide the number exactly, the function returns false.

The printListFactors function prints a list of all factors of the given number. We loop through all numbers that are less than half the given number and check if the number is divisible by that value. If it is, we print that value as a factor.

You can call these functions like this:

main.swift
let number = 13
if checkIfNumberIsPrime(number) {
    print("\(number) is prime")
} else {
    print("\(number) is composite")
    print("Factors: ")
    printListFactors(number)
}
181 chars
9 lines

This would output:

main.swift
13 is prime
12 chars
2 lines

gistlibby LogSnag