October 13, 2024

Automorphic Number in Python

An automorphic number (or circular number) is a number whose square ends with the same digits as the number itself. For example, 5 is an automorphic number because (5^2 = 25), which ends in 5.

1. Definition and Example

A number n is considered automorphic if the last digits of n^2 are the same as n. For example:

  • 25 is an automorphic number because (25^2 = 625), which ends in 25.
  • 76 is an automorphic number because (76^2 = 5776), which ends in 76.
  • 13 is not an automorphic number because (13^2 = 169), which does not end in 13.

2. Python Program to Check Automorphic Number

def is_automorphic(number):
    # Calculate the square of the number
    square = number ** 2
    
    # Convert both the number and its square to strings
    num_str = str(number)
    square_str = str(square)
    
    # Check if the square ends with the number
    return square_str.endswith(num_str)

# Example usage
num = 25
if is_automorphic(num):
    print(f"{num} is an automorphic number.")
else:
    print(f"{num} is not an automorphic number.")
    

3. Explanation

In this code:

  • The function is_automorphic calculates the square of the given number.
  • It converts both the original number and its square to strings to check if the square ends with the number.
  • The endswith() method is used to verify if the string representation of the square ends with the string representation of the original number.

4. Conclusion

The provided Python program demonstrates how to check if a number is automorphic by comparing the end of its square with the number itself. This concept can be used for various mathematical and algorithmic applications.