我试图做一个函数来返回所有素因子,但我认为我的逻辑中存在错误。这是功能:
func getPrimeFactors(numToCheck:Int) -> Int {
if numToCheck == 1 { return numToCheck}
var primeFactors:Array<Int> = []
var n = numToCheck
var divisor = 2
while n > divisor && n%divisor == 0 {
primeFactors.append(divisor)
n = n/2
}
for i in stride(from: 3, to: sqrt(Double(n)), by:2) {
while n > Int(i) && n%Int(i) == 0 {
primeFactors.append(Int(i))
n = n/3
}
}
if n > 1 {
primeFactors.append(n)
}
print(primeFactors)
return 0
}
忽略回报,我将在以后使用它。如果我插入1000作为数字来检查我的阵列最终[2,2,2,5,41]。我出错的任何想法?
由于