Skip to Main Content
Blog

Print all Automorphic Numbers in Python

Print all Automorphic Numbers in Python

Enter lower bound: 1
Enter upper bound: 999
1, 5, 6, 25, 76, 376, 625,
def main():
	"""
	Prints all the Automorphic numbers within a given range.
	"""

	a = int(input("Enter lower bound: "))
	b = int(input("Enter upper bound: "))

	for i in range(a, b + 1):
		if is_automorphic(i):
			print(i, end=", ")
	print()


def is_automorphic(number: int):
	"""
	Checks if a number is an Automorphic number or not.
	"""

	# Check if the number is positive
	if number < 0:
		return False

	BASE = 10

	# Find the square of the number
	squared = number * number

	# Compare the digits of the numbers from the last
	while number != 0:
		squared_unit_digit = squared % BASE
		unit_digit = number % BASE
		if squared_unit_digit != unit_digit:
			return False
		squared //= BASE
		number //= BASE
	return True


if __name__ == "__main__":
	main()