用 Python 编写程序,根据给定的 n 找出给定序列的最后一位数字

pythonserver side programmingprogramming更新于 2026/2/1 10:20:17

假设我们有一个值 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 有效,所以

  • 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 +(4 当 n 为奇数时,否则为 0)) 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

相关文章


有用资源