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

示例

让我们看看下面的实现来更好地理解:

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

更新于:2021年10月25日

浏览量:171

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.