pythonpython-3.x

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.

My code looks like this. I am just a beginner in python. I am not getting the output desired.

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)

Solution

  • I am assuming you are looking for something like this:

    power: 8

    digits: 2

    2 ^ 8 = 256

    last two digits = 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)