Loading [MathJax]/jax/output/HTML-CSS/jax.js

Python程序:求给定序列在给定n下的最后一位数字


假设我们有一个值n。我们需要找到序列S的最后一位数字。S的方程如下:

αi=02innj=022i+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

示例

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

Open Compiler
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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

6

更新于:2021年10月25日

浏览量:171

开启你的职业生涯

完成课程获得认证

开始学习
广告