I have a function to return the factorial of a value passed in and then I am trying to get each of the digits in that result and find the sum of all of them. This works well until the number becomes too large and imprecise.
Currently, my return sum is 87 for 100!.
Is there a way to achieve a correct sum using only Playgrounds, i.e not being able to import a BigInt framework?
import Foundation
var result : Double = 0
var sum = 0
func fact(value : Double) -> Double {
if value == 1 {
return 1
} else {
result = fact(value: value - 1) * value
return result
}
}
fact(value: 100)
var digits = Array(String(result)).map{Int(strtoul((String($0)),nil,16))}
for digit in digits {
sum = sum + digit
}
print("The sum is: \(sum)")