【问题标题】:How to calculate 2 to the power of a large number modulo another large number?如何计算一个大数的 2 的幂模另一个大数?
【发布时间】:2019-12-08 11:09:12
【问题描述】:

M = 115792089237316195423570985008687907853269984665640564039457584007908834671663

296514807760119017459957299373576180339312098253841362800539826362414936958669 % M = ?

是否可以在 Python 中进行计算?还是有其他方法?

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 我可以试试 sagemath,但数量巨大:(
  • 你想要三个参数pow。见docs.python.org/3/library/functions.html#pow
  • 这能回答你的问题吗? pow or ** for very large number in Python
  • 你知道96514807760119017459957299373576180339312098253841362800539826362414936958669有多大吗?要仅循环 2⁶⁴ 次,您需要大约 292 年,假设您每秒可以循环 20 亿次。这个数字远远大于 2⁶⁴,所以你在宇宙的生命周期中无法得到modular exponentiation。您也无法计算实际功率,因为​​宇宙中只有大约 10⁸⁰ 粒子,这意味着您没有足够的粒子来存储)

标签: python math modular modular-arithmetic


【解决方案1】:

为了计算结果,@MarkDickinson 在 cmets 中提到,三参数 pow 可以有效地执行此操作。

这是如何工作的简化解释:

  • 计算2**N mod M,先找到K = 2**(N//2) mod M
  • 如果N 是偶数,2**N mod M = K * K mod M
  • 如果N 是奇数,2**N mod M = K * K * 2 mod M 这样,就不需要计算巨大的数字了。实际上,pow 使用的技巧更多,更通用,不需要递归。

这里是一些演示代码:

def pow_mod(B, E, M):
    if E == 0:
        return 1
    elif E == 1:
        return B % M
    else:
        root = pow_mod(B, E // 2, M)
        if E % 2 == 0:
            return (root * root) % M
        else:
            return (root * root * B) % M

M = 115792089237316195423570985008687907853269984665640564039457584007908834671663
E = 96514807760119017459957299373576180339312098253841362800539826362414936958669

print(pow_mod(2, E, M))
print(pow(2, E, M))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2011-05-05
    • 2018-05-28
    • 2012-07-06
    • 2017-04-03
    • 2019-12-05
    相关资源
    最近更新 更多