0

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)")
brandan
  • 57
  • 9
  • 100! has 158 decimal digits, no built-in type has a that much precision. – Martin R Jul 16 '18 at 20:43
  • @MartinR Thanks for the quick reply. So, I really would need to use something like BigInt to perform this task accurately? – brandan Jul 16 '18 at 20:45
  • Either that, or use an *array* of integers to represent the number. – Trying to solve https://projecteuler.net/problem=20 ? – Martin R Jul 16 '18 at 20:46
  • …which would essentially be implementing your own `BigInt` type. This is [Project Euler problem #20](https://projecteuler.net/problem=20) by the way. If you (Brandan) intend to continue on with Project Euler, you'll definitely need a big-integer type. – rob mayoff Jul 16 '18 at 20:47
  • Yes, this is problem 20 on Project Euler. I'm using them for practice in playgrounds, then started wondering if playgrounds had limitations or not. I'll look into the array method now and hopefully be able to get this finished. – brandan Jul 16 '18 at 20:55
  • 1
    Take a look at what I did in [this answer](https://stackoverflow.com/a/43830823/1630618). – vacawama Jul 16 '18 at 21:05

0 Answers0