简体   繁体   English

获取long的最后n位

[英]Get the last n digits of a long

My program asks user to enter a power and how many digits they want.我的程序要求用户输入幂和他们想要的数字。 And finds the last that many digits of 2 raised to the power the user entered.并找到用户输入的 2 的最后一位数。

My code looks like this.我的代码看起来像这样。 I am just a beginner in python.我只是 python 的初学者。 I am not getting the output desired.我没有得到想要的 output。

temp = int(input('Enter the power of the number: '))
temp2 = int(input('Enter the no.of digits you want: '))
temp3 = (2 ** temp) // temp2
temp4 = (temp3 % 100)
print('The last that many digits of the number raised to the power is is:',temp4)

I am assuming you are looking for something like this:我假设你正在寻找这样的东西:

power: 8功率:8

digits: 2位数:2

2 ^ 8 = 256 2 ^ 8 = 256

last two digits = 56最后两位数 = 56

To do this your code would look like this:为此,您的代码将如下所示:

power = int(input('two to the power of '))
digits = int(input('last how many digits? '))

num = 2 ** power # calculate power
num = num % (10 ** digits) # get remainder of division by power of 10
print(num)

Here's another approach:这是另一种方法:

power = int(input('two to the power of '))
digits = int(input('last how many digits? '))

num = 2 ** power # calculate power
num = str(num) # convert with string to work with
num = num[-digits:] # get last n digits
num = int(num)
print(num)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM