[英]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.