1

I have been working on a hacker rank problem where I have to print a number which is a factorial of 25. Here is the code I used.

func extraLongFactorials(n: Int) -> Void {
    let factorialNumber = factorial(number: n)

    var arrayForStorage: [Int] = []

    var loop = factorialNumber
    while (loop > 0) {
       let digit = loop.truncatingRemainder(dividingBy: 10)

       arrayForStorage.append(Int(digit))

       loop /= 10
    }

    arrayForStorage = arrayForStorage.reversed()
    var returnString = ""
    for element in arrayForStorage {
       returnString = "\(returnString)\(element)"
    }

    print(returnString)
}

func factorial(number: Int) -> Double {
    if number == 0 || number == 1 {
       return 1
    } else if number == 2 {
       return 2
    } else {
       return Double(number) * factorial(number: number - 1)
    }
}

But when I try to print the factorial number it just prints 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015511210043330982408266888 when it should print 15511210043330985984000000.

I think for a Double number truncatingRemainder(dividingBy: 10) method is not giving me the exact number of the remainder. Because when I tried to print the truncatingRemainder of 15511210043330985984000000 it is giving me as 8. Here is the code.

let number: Double = 15511210043330985984000000
print(number.truncatingRemainder(dividingBy: 10))

So finally I didn't find any solution for the problem of how to split the large number and add it into an array. Looking forward for the solution.

Shreesha Kedlaya
  • 340
  • 4
  • 19

1 Answers1

1

Type Double stores a number as a mantissa and an exponent. The mantissa represents the significant figures of the number, and the exponent represents the magnitude of the number. A Double can only represent about 16 significant figures, and your number has 26 digits, so you can't accurately store 15511210043330985984000000 in a Double.

let number1: Double = 15511210043330985984000000
let number2: Double = 15511210043330985984012345

if number1 == number2 {
    print("they are equal")
}
they are equal

You will need another approach to find large factorials like the one shown in this answer.

vacawama
  • 150,663
  • 30
  • 266
  • 294