需要注意的是,一个质数可能会在gcd中多次进入,因此需要一些重复循环......
let arr = [4, 8, 12] // [2,4,6,8,10]
// 1. build the list of prime numbers (up to 100 is enough to test GCD of numbers upto 10_000). You could also build this list by code.
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
// 2. Find the min in your array. No need to test divisor beyond the min, to speed up
var minimum = arr.min() ?? 1
// 3. Loop through primes to test as divisor or minumum element
var goOn = true
var possibleDivisors : [Int] = []
for prime in primes where minimum > 1 {
var primeAtPower = 1
repeat { // A same prime may be multiple times in gcd. ex: arr = [4, 8, 12]: 2 will appear twice as divisor of 4
if minimum % prime == 0 {
primeAtPower *= prime
minimum /= prime
} else {
goOn = false
}
goOn = goOn && minimum > 1
}
while goOn
possibleDivisors.append(primeAtPower)
}
var gcd = 1 // Initialize
for divisor in possibleDivisors {
var possibleDivisor = true
for val in arr where possibleDivisor {
if val % divisor != 0 { possibleDivisor = false }
}
// 4. If common divisor, gcd includes it
if possibleDivisor { gcd *= divisor }
}
print("gcd of \(arr) is", gcd)
产量
[4, 8, 12] 的 gcd 为 4