Python Program to Find Automorphic Number
str(square).endswith(str(number)).Examples
How to Think About It
Algorithm
Code
number = int(input("Enter a number: ")) square = number ** 2 if str(square).endswith(str(number)): print(f"{number} is an automorphic number") else: print(f"{number} is not an automorphic number")
Dry Run
Let's trace the number 5 through the code
Input number
number = 5
Calculate square
square = 5 ** 2 = 25
Convert to strings
str(square) = '25', str(number) = '5'
Check if square ends with number
'25'.endswith('5') is True
Print result
Output: '5 is an automorphic number'
| number | square | str(square) | str(number) | endswith check |
|---|---|---|---|---|
| 5 | 25 | '25' | '5' | True |
Why This Works
Step 1: Square the number
We find the square because automorphic numbers have their square ending with the number itself.
Step 2: Convert to strings
Converting to strings allows easy comparison of the ending digits using endswith.
Step 3: Check ending digits
Using endswith checks if the square's string ends exactly with the number's string.
Alternative Approaches
number = int(input("Enter a number: ")) length = len(str(number)) square = number ** 2 if square % (10 ** length) == number: print(f"{number} is an automorphic number") else: print(f"{number} is not an automorphic number")
def is_automorphic(num): square = num ** 2 def check(n, sq): if n == 0: return True if n % 10 != sq % 10: return False return check(n // 10, sq // 10) return check(num, square) number = int(input("Enter a number: ")) if is_automorphic(number): print(f"{number} is an automorphic number") else: print(f"{number} is not an automorphic number")
Complexity: O(d) time, O(1) space
Time Complexity
The time depends on the number of digits d in the input number because string conversion and endswith check operate on digit length.
Space Complexity
Only a few variables and string conversions are used, so space is constant O(1).
Which Approach is Fastest?
The modulo method is generally faster than string conversion because it uses arithmetic operations without creating new strings.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String endswith | O(d) | O(1) | Readability and simplicity |
| Modulo operator | O(d) | O(1) | Performance and no string use |
| Recursive digit check | O(d) | O(d) | Learning recursion and digit manipulation |
str(square).endswith(str(number)) for a simple and readable automorphic check.