如何快速处理长整数的答案

时间:2019-01-24 11:01:13

标签: swift rsa long-integer modulus pow

我必须迅速计算两个长整数的幂。 Swift给出NaN错误(不是数字),并且无法回答。

例如

  

战俘(2907,1177)

用于计算功率并获取余数(a^b % n) where a= 2907, b= 1177, n= 1211

的主进程ID

任何准则如何解决?

1 个答案:

答案 0 :(得分:3)

您将必须使用1.外部框架或2.自己进行操作。

1。外部框架

我认为您可以尝试:https://github.com/mkrd/Swift-Big-Integer

let a = BInt(2907)
let b = 1177
let n = BInt(1211)

let result = (a ** b) % n

print(result) // prints 331

注意:Cocoapods导入失败,因此我刚刚导入了此文件以使其正常工作:https://github.com/mkrd/Swift-Big-Integer/tree/master/Sources

2。 DIY : 使用Modulus power of big numbers

的答案
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

3。奖励:使用与2相同的方法,但要感谢http://natecook.com/blog/2014/10/ternary-operators-in-swift/

,并使用自定义三元运算符
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

其他信息: 仅用于二进制2907 ^ 1177的信息需要13542位... https://www.wolframalpha.com/input/?i=2907%5E1177+in+binary

需要4kb的字符串才能将其存储在基数10中:https://www.wolframalpha.com/input/?i=2907%5E1177

相关问题