find the greatest common divisor of a list of numbers in swift

Here is a function in Swift that finds the greatest common divisor of a list of numbers:

main.swift
func findGCD(numbers: [Int]) -> Int {
    // Get the smallest number in the list
    guard let minNumber = numbers.min() else {
        return 1
    }

    // Find the greatest common divisor using Euclid's algorithm
    var divisor = 2
    var gcd = 1
    while divisor <= minNumber {
        if numbers.allSatisfy({ $0 % divisor == 0 }) {
            gcd = divisor
            divisor += 1
        } else {
            divisor += 1
        }
    }

    return gcd
}
468 chars
21 lines

Here's how it works:

  1. The function takes an array of integers as input.
  2. First, we get the smallest number in the list using the min() method. If the list is empty, we return 1 as the greatest common divisor.
  3. Next, we use Euclid's algorithm to find the greatest common divisor. We start by initializing a divisor variable to 2 and a gcd variable to 1.
  4. We loop through all the numbers from 2 to the smallest number in the list. For each number, we check if it is a common divisor of all the numbers in the list using the allSatisfy() method. If it is, we update the gcd variable to the current divisor and increment divisor by 1. If it is not, we simply increment divisor by 1.
  5. Finally, we return the gcd variable as the greatest common divisor of the list.

Note that this implementation assumes that all the numbers in the list are positive integers. If the list contains negative numbers or floating point numbers, additional checks and conversions may be necessary.

gistlibby LogSnag