如何处理swift中长整数的回答

如何处理swift中长整数的回答,swift,rsa,long-integer,modulus,pow,Swift,Rsa,Long Integer,Modulus,Pow,我必须计算swift中两个长整数的幂。 斯威夫特给出了一个错误NaN(不是数字),但没有回答 例如 战俘(29071177) 用于计算功率并获取余数的主进程id(a^b%n),其中a=2907,b=1177,n=1211 有什么解决方法吗?您必须使用1。外部框架或2。你自己做吧 1。外部框架: 我想你可以试试: 注意:Cocoapods导入失败,因此我仅导入此文件以使其正常工作: 2。DIY: 使用 3。奖金:使用与2相同的奖金。但由于 然后你可以打电话: let result = 2907 *

我必须计算swift中两个长整数的幂。 斯威夫特给出了一个错误NaN(不是数字),但没有回答

例如

战俘(29071177)

用于计算功率并获取余数的主进程id
(a^b%n),其中a=2907,b=1177,n=1211


有什么解决方法吗?

您必须使用1。外部框架或2。你自己做吧

1。外部框架

我想你可以试试:

注意:Cocoapods导入失败,因此我仅导入此文件以使其正常工作:

2。DIY: 使用

3。奖金:使用与2相同的奖金。但由于

然后你可以打电话:

let result = 2907 *%* 1177 %*% 1211

其他信息: 仅用于二进制2907^1177中的信息需要13542位。。。


它需要一个4kb的字符串来存储在10进制中:

pow
仅适用于浮点,NaN是IEEE 754浮点“值”。此外,它看起来像是在尝试执行
模幂运算,这有一个特殊的功能。您根本不需要计算
a^b
的完整值。@穆巴沙尔,如果答案对您有效,请毫不犹豫地接受它。第二点。DIY:使用大数模幂的答案是获得长数模的正确选择。
func powerMod(base: Int, exponent: Int, modulus: Int) -> Int {
    guard base > 0 && exponent >= 0 && modulus > 0
        else { return -1 }

    var base = base
    var exponent = exponent
    var result = 1

    while exponent > 0 {
        if exponent % 2 == 1 {
            result = (result * base) % modulus
        }
        base = (base * base) % modulus
        exponent = exponent / 2
    }

    return result
}

let result = powerMod(base: 2907, exponent: 1177, modulus: 1211)

print(result) // prints 331
precedencegroup ModularityLeft {
    higherThan: ComparisonPrecedence
    lowerThan: AdditionPrecedence
}

precedencegroup ModularityRight {
    higherThan: ModularityLeft
    lowerThan: AdditionPrecedence
}

infix operator *%* : ModularityLeft
infix operator %*% : ModularityRight

func %*%(exponent: Int, modulus: Int) -> (Int) -> Int {
    return { base in
        guard base > 0 && exponent >= 0 && modulus > 0
            else { return -1 }

        var base = base
        var exponent = exponent
        var result = 1

        while exponent > 0 {
            if exponent % 2 == 1 {
                result = (result * base) % modulus
            }
            base = (base * base) % modulus
            exponent = exponent / 2
        }

        return result
    }
}

func *%*(lhs: Int, rhs: (Int) -> Int) -> Int {
    return rhs(lhs)
}
let result = 2907 *%* 1177 %*% 1211