繁体   English   中英

使用 python 在 SPOJ 中超出时间限制

[英]Time limit exceeded in SPOJ using python

我正在尝试在 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 因为你得到 TLE,而是因为你申请这个问题的方法。 您可以使用一种称为Binary Exponentiation的技术来解决这个问题。 这里阅读并尝试自己编写解决方案。

代码:

# 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))

暂无
暂无

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

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