You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:获取2的指定幂次的最后n位数字代码问题

Fixing Your "Last Digits of 2^power" Code

Hey there! Let's break down what's off with your current code and fix it up so it does exactly what you want—grabbing the last N digits of 2 raised to a given power.

What's Wrong With the Original Code?

Looking at your code, two key logic mistakes are tripping you up:

  • You're using (2 ** temp) // temp2 — dividing by the number of digits you want has nothing to do with isolating the last N digits. That operation just shrinks the number arbitrarily, not targeting the end digits.
  • You're hardcoding % 100 at the end, which only gives you the last 2 digits no matter what number the user inputs for temp2.

How to Fix It

To get the last N digits of a number, you need to calculate the number modulo 10^N (10 raised to the power of N). That's because modulo 10 keeps the last digit, modulo 100 keeps the last two, modulo 1000 keeps the last three, and so on.

Plus, for very large powers (like 100000), calculating 2 ** temp directly can be slow and use a lot of memory. Python's built-in pow() function can handle this efficiently with three arguments: pow(base, exponent, mod) computes (base^exponent) % mod without generating the huge intermediate number.

Corrected Code

power = int(input('Enter the power of the number: '))
num_digits = int(input('Enter the number of digits you want: '))

# Calculate the modulus we need (10^num_digits)
modulus = 10 ** num_digits
# Efficiently compute 2^power mod modulus
last_digits = pow(2, power, modulus)

# Optional: Format to show leading zeros if needed (e.g., 24 becomes 024 for 3 digits)
print(f'The last {num_digits} digits of 2^{power} are: {last_digits:0{num_digits}d}')

Let's Test It

For example:

  • If you input power=10 and num_digits=3, the code returns 024 (since 2^10=1024, last 3 digits are 024)
  • If you input power=5 and num_digits=2, it returns 32 (2^5=32, last 2 digits are 32)
  • For power=20 and num_digits=4, it returns 7616 (2^20=1048576, last 4 digits are 7616)

Bonus Notes

  • The :0{num_digits}d in the print statement adds leading zeros to make sure the output always has exactly num_digits characters. If you don't want leading zeros (e.g., just 24 instead of 024), you can remove that part and just use print(f'The last {num_digits} digits...: {last_digits}').
  • Using pow(2, power, modulus) is way more efficient for large powers than calculating 2**power first—give it a try with power=100000, it'll return instantly!

内容的提问来源于stack exchange,提问作者kalium

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:36:29