Python新手求助:获取2的指定幂次的最后n位数字代码问题
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
% 100at the end, which only gives you the last 2 digits no matter what number the user inputs fortemp2.
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}din the print statement adds leading zeros to make sure the output always has exactlynum_digitscharacters. If you don't want leading zeros (e.g., just24instead of024), you can remove that part and just useprint(f'The last {num_digits} digits...: {last_digits}'). - Using
pow(2, power, modulus)is way more efficient for large powers than calculating2**powerfirst—give it a try with power=100000, it'll return instantly!
内容的提问来源于stack exchange,提问作者kalium

