Editor

Python Program to Check an Automorphic Number

Beginner · Numbers

An automorphic number is a number whose square ends in the number itself. 76 is automorphic because 76 x 76 = 5776, which ends in 76, and 5 (square 25) and 25 (square 625) are automorphic too.

Program

automorphic_number.py
num = 76 # or: num = int(input("Enter a number: "))
square = num * num
digits = len(str(num))
# The remainder after dividing by 10, 100, 1000... is the last 1, 2, 3... digits
last_part = square % (10 ** digits)
print(f"Square of {num}: {square}")
print(f"The last {digits} digit(s) of the square: {last_part}")
if last_part == num:
print(num, "is an automorphic number")
else:
print(num, "is not an automorphic number")
Output
Square of 76: 5776
The last 2 digit(s) of the square: 76
76 is an automorphic number

How it works

  1. num * num gives the square, 5776.
  2. len(str(num)) counts the digits of the number, which is how many digits to compare at the end of the square.
  3. square % (10 ** digits) keeps the last digits: 5776 % 100 is 76.
  4. If those last digits equal the number, it is automorphic.

Other ways to write it

Using endswith()

Using endswith()
for num in [5, 6, 7, 25, 76, 376, 100]:
square = num * num
if str(square).endswith(str(num)):
print(f"{num} x {num} = {square}: automorphic")
else:
print(f"{num} x {num} = {square}: not automorphic")
Output
5 x 5 = 25: automorphic
6 x 6 = 36: automorphic
7 x 7 = 49: not automorphic
25 x 25 = 625: automorphic
76 x 76 = 5776: automorphic
376 x 376 = 141376: automorphic
100 x 100 = 10000: not automorphic

Comparing the numbers as text with endswith() avoids working out powers of 10.

All automorphic numbers below 10000

All automorphic numbers below 10000
found = []
for n in range(1, 10000):
if (n * n) % (10 ** len(str(n))) == n:
found.append(n)
print("Automorphic numbers below 10000:", found)
Output
Automorphic numbers below 10000: [1, 5, 6, 25, 76, 376, 625, 9376]

They are rare: below 10000 there are only 1, 5, 6, 25, 76, 376, 625 and 9376.

Try it yourself

Find the next automorphic number after 9376 by raising the limit of the search.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises