【问题标题】:Time limit exceeded in SPOJ using python使用 python 在 SPOJ 中超出时间限制
【发布时间】:2020-05-05 06:41:18
【问题描述】:

我正在尝试在 SPOJ https://www.spoj.com/problems/LASTDIG/ 上解决此问题,我确信代码是正确的,但是当我在它显示的网站上提交它时,超出了时间限制,

问题的解决代码是:

t=int(input()) #for test cases
for i in range(0,t):
         x,y=input().split() #for  two seperate input
         a=int(x)
         b=int(y)
         if 0<=a<=20 and 0<=b<=2147483000:   #conditions for  input
                 z=x**y
                 c=str(z)
                 print(c[-1]) #finally to print the last digit of the number

我怀疑可能是程序太简单了,较大的输入需要时间?那么,任何人都可以建议如何改进解决方案,还是我需要选择其他语言,如 C++?

【问题讨论】:

    标签: python python-3.x array-algorithms


    【解决方案1】:

    这不是由于您获得 TLE 的 python,而是由于您申请此问题的方法。 您可以使用一种称为Binary Exponentiation 的技术来解决这个问题。 从here 阅读它并尝试自己编写解决方案。

    代码:

    # calculates (x ^ y) % m using binary exponentiation 
    def binpow(x, y, m) :
        x = x % m
        ans = 1
        while y > 0 :
            if y % 2 == 1 :
                ans = (ans * x) % m
            x = (x * x) % m
            y = y >> 1
        return ans
    
    for _ in range(int(input())) :
        a, b = map(int, input().split())
        print(binpow(a, b, 10))
    

    【讨论】:

      猜你喜欢
      • 2016-04-07
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多