Search code examples
pythoninteger

How can we find the unit digits of a specific number?


I'm just wondering if there is a code in python to find what is the units digit of a number that I inputed.

Number = int(input('Enter a number:'))
print(Number)
while Number >= 100:
  print(Number-) #That's a minus sign.

Btw yes, I'm trying to do a program which accepts as input a positive integer and checks, using an algorithm, to see whether or not the integer is divisible by 11. This particular test for divisibility by 11 was given in 1897 by Charles L. Dodgson.

So I need to remove the units digit of the number, then subtract the number by the units digit, until it reaches a two digit number, where we calculate if it is divisible by 11.


Solution

  • It looks like the problem description is not complete. The algorithm could be:

    • shorten the number by leaving out the units
    • subtract the units once again from the number
    • multiply the number by -1

    The end result will be the number modulo 11, although it could be negative.

    num = int(input('Enter a number:'))
    print("Given number:   ", num, "   Trying to find num % 11 =", num % 11)
    while abs(num) >= 11:
        units = num % 10
        num //= 10  # integer division
        num -= units
        num = -num
        print("Modified number:", num)
    if num < 0:
        num += 11
    print("Result:", num)
    

    A simplified algorithm, without the pesky num = -num that just checks for divisibility by 11:

    num = int(input('Enter a number:'))
    print("Given number:   ", num, "   Trying to find num % 11 == 0 :", num % 11 == 0)
    given_number = num
    while num >= 100:
        units = num % 10  # find the last digit
        num //= 10  # integer division (i.e. remove the last digit)
        num -= units  # subtract the just found last digi
        print("Modified number:", num)
    
    if num in [0, 11, 22, 33, 44, 55, 66, 77, 88, 99]:
        print(given_number, "is divisible by 11")
    else:
        print(given_number, "is NOT divisible by 11")