简体   繁体   中英

Time limit exceeded in SPOJ using python

I am trying to solve this problem on SPOJ, https://www.spoj.com/problems/LASTDIG/ , I am sure the code is correct but when I submit it on the site it shows, time limit exceeded,

The solution code for the problem is:

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

I suspect maybe the program is too simple and time taking for larger inputs? So, can anyone please suggest how to improve the solution or do I need to choose a different language like C++?

It's not python due to which you are getting TLE, it's due to the approach that you are applying for this question. You can solve this question using a technique called Binary Exponentiation . Read about it from here and try to code the solution yourself.

code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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