Disclaimer: There are similar questions to this one on SO, however they all either don't address the efficiency of an algorithm or are written in a different language. See this answer which talks about efficiency in python and see if it helps you answer my question.
So I need the most efficient way to find all of the factors of any given number that works quickly with very large numbers. I already have several iterations of code that works but takes a very long time to process numbers with more than 6 characters.
Edit: upon request here are some of my non-efficient ways of doing this (error-checking left out for clarity)
Really messy:
@IBAction func findFactorsButton(_ sender: AnyObject) {
if let _ = textField.text, !textField.text!.isEmpty {
counter = 1
factors = []
repeat {
counter += 1
if Int(textField.text!)! % counter == 0 {
factors.append(String(counter))
} else {
continue
}
} while counter != Int(textField.text!)
factors.removeLast()
outputLabel.text = factors.joined(separator: ", ")
} else {
outputLabel.text = ""
}
}
Less messy solution (playground):
func calculateFactors(n: Int) -> String {
var result: String = ""
for i in 1...n {
guard n % i == 0 else {continue}
result += i == 1 ? "1" : ", \(i)"
}
print(result)
return result
}