簡體   English   中英

我在優化大量代碼時遇到問題

[英]I'm having trouble optimizing my code on large numbers

輸入的第一行包含三個由單個整數分隔的整數

間隔:,,, 其中 1 < ≤ 1000000 / 0 < ≤ 10000 和 1 < ≤ 10000 N - 最大功率 x - 一定量的輸入 n - 用於限制 output 使用模運算的總和。 下一行是 - 1 行,每行包含一個非負 integer 不超過 10000 例如對於輸入數據:5 2 100 2 8 1 3 正確的結果是:84 因為

2 * (2**2) = 8
8 * (2**3) = 64
1 * (2**4) = 16
3 * (2**5) = 96
8 + 64 + 16 + 96 = 184
184 % 100 = 84

這是我的 python 代碼,我需要針對更大的變量進行優化:

N, x, n = map(int, input().split())
sum = 0
for power in range(2,N+1):
   sum+= (int(input())* (x**power))
   sum = sum%n 
print(sum)

預先感謝您的幫助

您可以像 go 一樣將模數應用於功率和結果。 此外,您可以通過在每次迭代中乘以 x 來積累功率,而不是使用大量數字(最終會變慢)

N, x, n = map(int, input().split())
result = 0
power  = x*x                         # x^2, x^3 ...
for _ in range(N-1):                 # read N-1 values 
    result += int(input())*power     # add product of power
    result %= n                      # reduce as you go with modulo
    power = power*x % n              # accumulate power (modulo n)
    
print(result) # 84

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM