计算python中较大数字的模数

时间:2016-12-28 14:09:42

标签: python python-3.x math modular-arithmetic

我的代码可以正常使用较小的数字但是当我使用大数字时它会产生运行错误

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)

INPUT:

2  
12 2 17  
523 3 11

输出:

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

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

对于适用于大数量的问题,没有天真的解决方案。你需要使用一些聪明的代数和/或数论。 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

例如,

>>> f(366, 457429086499,164868357)
2013258

几乎是瞬间计算的。