0

I am solving a question from HackerRank which asks to print the value of extra-long factorials that can't be stored even in a 64-bit long variable.

I am using NSDecimalNumber to store the value. However, even in this case, the final result is rounded off.

func extraLongFactorials(n: Int) -> Void
{
    var factorial: NSDecimalNumber = 1
    for index in 1...n
    {
        let indexInNSDecimal = NSDecimalNumber(value: index)
        factorial = factorial.multiplying(by: indexInNSDecimal)
    }
    let factorialWithoutRounding = factorial.description(withLocale: nil)
    print(factorialWithoutRounding)
}

print(extraLongFactorials(n: 45)) // 119622220865480194561963161495657715064000000000000000000

However, the result should be 119622220865480194561963161495657715064383733760000000000.

This link talks about using description(withLocale:). NSDecimalNumber round long numbers

However, it does not clearly explain how to use the description(withLocale:) method. I also went through the apple doc https://developer.apple.com/documentation/foundation/nsdecimalnumber/1412789-description. But it also does not explain clearly how to use it.

Can someone please discuss this method in detail.

Nilanshu Jaiswal
  • 1,583
  • 3
  • 23
  • 34
  • The precision of NSDecimalNumber is limited to 38 decimal digits. That is not enough for your task. – Martin R Oct 20 '19 at 06:42
  • @MartinR Is there any other way of saving numbers that require more than 38 digits of precision? – Nilanshu Jaiswal Oct 20 '19 at 07:01
  • Have a look at https://stackoverflow.com/questions/43830151/swift-3-calculate-factorial-number-result-becomes-too-high and https://stackoverflow.com/questions/25531914/biginteger-equivalent-in-swift – Martin R Oct 20 '19 at 07:07

0 Answers0