Python程式:求給定序列在給定n下的最後一位數字
假設我們有一個值n。我們需要找到序列S的最後一位數字。S的方程如下:
$$\sum_{i=0\: 2^{^{i}}\leqslant n}^{\alpha } \sum_{j=0}^{n} 2^{2^{^{i}+2j}}$$
因此,如果輸入為n = 2,則輸出為6,因為:這裡只有i = 0和i =1有效,所以
- S0 = 2^(2^0 + 0) + 2^(2^0 + 2) + 2^(2^0 + 4) = 42
- S1 = 2^(2^1 + 0) + 2^(2^1 + 2) + 2^(2^1 + 4) = 84 總和是42+84 = 126,所以最後一位數字是6。
為了解決這個問題,我們將遵循以下步驟:
- total:= 0
- temp := 1
- 當 temp <= n 時,執行以下操作:
- total := total + (2^temp mod 10)
- temp := temp * 2
- total := total * (1 +(當n為奇數時為4,否則為0)) mod 10
- total := total + (2^temp mod 10)
- 返回 total
示例
讓我們看看下面的實現來更好地理解:
def solve(n): total= 0 temp = 1 while (temp <= n): total += pow(2, temp, 10) temp *= 2 total = total * (1 + (4 if n %2 ==1 else 0)) % 10 return total n = 2 print(solve(n))
輸入
2
輸出
6
廣告