简体   繁体   English

Python中的模幂运算

[英]Modular Exponentiation in Python

I was trying to solve the ZSUM problem at SPOJ using Python 2.7.9 as my coding language and designed a program to do so. 我试图使用Python 2.7.9作为我的编码语言来解决SPOJ上的ZSUM问题,并设计了一个程序来解决这个问题。 As the code runs perfectly but gives a TLE at the judge, I guess it is not fast enough. 由于代码可以完美运行,但是会给评委一个标题,所以我认为它不够快。 Is there is possible to optimize the below code to meet the judge requirement or it is impossible to beat the challenge using Python. 是否有可能优化下面的代码以满足法官的要求,或者使用Python克服挑战。

Link to the problem: http://www.spoj.com/problems/ZSUM/ 链接到问题: http : //www.spoj.com/problems/ZSUM/

def zsum(n,k):
  a=2*pow(n-1,k,10000007)
  b=pow(n,k,10000007)
  c=2*pow(n-1,n-1,10000007)
  d=pow(n,n,10000007)
  zsum=(a+b+c+d)%10000007
  print zsum

def main():
  while True:
    n,k=map(int,raw_input().split())
    if n==k==0:
        break
    else:
        zsum(n,k)
 main()

I don't know if this will help (if you read the problem's comments you will see someone saying that it is impossible to solve in Python - that can happen on online judges with slower languages) but you can optimize the code: 我不知道这是否有帮助(如果您阅读问题的注释,您会看到有人说无法用Python解决-这种情况可能会在使用较慢语言的在线法官身上发生),但是您可以优化代码:

def zsum(n,k):
  a=2*pow(n-1,k,10000007)   # (1)
  b=pow(n,k,10000007)       # (2)
  c=2*pow(n-1,n-1,10000007) # (1)
  d=pow(n,n,10000007)       # (2)
  zsum=(a+b+c+d)%10000007
  print zsum

Note that in (1) , you are computing pow(n - 1, min(k, n - 1)) twice. 请注意,在(1) ,您要计算pow(n - 1, min(k, n - 1))两次。 You could compute it once and then use modular exponentiation only for what is left. 您可以计算一次,然后仅对剩下的使用模幂。 Same for (2) . (2)相同。

Since there are zero accepted python solutions in a total of 2335 successful submissions, i think, no matter how much you optimise your solution, it is unlikely to manage to get accepted with python. 由于总共2335个成功的提交中有零个被接受的python解决方案,所以我认为,无论您如何优化解决方案,都不太可能被python接受。 Although python is a very useful language, it is not preferred in programming contests, as it is extremely slow (compared to C/C++ for instance). 尽管python是一种非常有用的语言,但它在编程竞赛中并不受欢迎,因为它非常慢(例如,与C / C ++相比)。 If you know how to code in C++ you should definitely give it a shot, although you must write you own modular exponentiation procedure. 如果您知道如何使用C ++进行编码,则尽管应该编写自己的模块化求幂过程,但您绝对应该尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM