python中大数模的计算

2024-04-24 12:47:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码在处理小数字时可以正常工作,但是当我处理大量的数字时,就会出现运行错误

n = int(input().strip())
a=[]
for a_i in range(n): 
  a,n,m = [int(a_temp) for a_temp in input().strip().split(' ')]

  #n = test cases
  #a is a number 
  # n is no of times a will repeat itself (for example a=12 ,n =2 so y=1212.)
  #m is divisor

  y=[a]*n
  #print(y)

  s = map(str, y)   # ['1','2','3']
  s = ''.join(s)          # '123'
  s = int(s)
  #print(s)

  mod=s%m
  print(mod)

输入:

^{pr2}$

输出:

5
6

输入如下:

2
366 457429086499 164868357
764 438211694736 385254849

它给出错误:

Traceback (most recent call last):
  File "C:/Users/LENOVO/AppData/Local/Programs/Python/Python35-32/try123.py", line 11, in <module>
    y=[a]*n
OverflowError: cannot fit 'int' into an index-sized integer

怎么解决这个问题?在


Tags: 代码intestmodforinputis错误
1条回答
网友
1楼 · 发布于 2024-04-24 12:47:47

对于这个问题,没有一个幼稚的解决办法,这对很多人都有效。你需要运用一些聪明的代数和/或数论。366, 366366, 366366366, ...是几何级数的部分和。有一个标准的公式来求和它们,但不幸的是,它涉及到除法,这在模运算中起不到很好的作用。This answer对于如何计算它们的问题,给出了一个聪明的递归解决方案,类似于模幂的标准方法。在Python中实现这一点,然后使用正确的参数调用它会导致:

def geom(a,k,n):
    """calculates (1 + a + a^2 + ... + a^(k-1)) mod n)"""
    if k <= 2:
        return sum(a**i for i in range(k)) % n
    else:
        m = k//2
        b = pow(a,2,n)
        g = ((1+a)*geom(b,m,n))%n
        return g if k%2 == 0 else (g + pow(a,k-1,n))%n

def f(a,m,n):
    """ returns aaaa...a (m times) modulo n"""
    k = len(str(a))
    r = pow(10,k,n)
    return (a*geom(r,m,n))%n

例如

^{pr2}$

几乎是瞬间计算出来的。在

相关问题 更多 >