如何在swift中以大量10个电源25打印所有数字?

时间:2018-06-08 09:36:53

标签: swift algorithm double factorial largenumber

我一直在研究黑客等级问题,我必须打印一个25的阶乘数。这是我使用的代码。

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)
    }
}

但是当我尝试打印阶乘数时,它只会在打印时打印0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015511210043330982408266888 15511210043330985984000000

我认为对于双号truncatingRemainder(dividingBy: 10)方法,我没有给出剩余的确切数字。因为当我尝试打印15511210043330985984000000的truncatingRemainder时,它给我8。这是代码。

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

所以最后我没有找到任何解决方法来解决如何分割大数字并将其添加到数组中的问题。期待解决方案。

1 个答案:

答案 0 :(得分:1)

类型Double会将数字存储为mantissaexponentmantissa表示数字的有效数字,exponent表示数字的大小。 Double只能代表大约16个有效数字,并且您的号码有26个数字,因此您无法在15511210043330985984000000中准确存储Double。< / p>

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

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

您需要另一种方法来查找this answer中显示的大型因子。