Check in Python if a number is an automorphic number

Mondo Education Updated on 2024-01-31

An isomorphic number means that the number appears to the right of its squared number.

For example: n = 25, n**2 = 25*25 = 625

The given number 25 appears to the right side of the result.

Therefore, 25 is an isomorphic number.

Algorithm:

Store the number to be detected in the variable num. Use the str() function to convert a given number to a string, and use the len() function to find the length of a given number, stored in the variable lenth. Calculate the square of a given number and store it in the variable sqr num. Use the modulo operation and the pow() function to get the last n digits of sqr num and store it in the variable n. Use the if conditional statement to check if n is equal to the given input number num. If the statement is true, the output of the given number is an isomorphic number. If false, the output of the given number is not an isomorphic number.

num = 25

lenth = len(str(num))

sqr_num = num**2

n = sqr_num % pow(10, lenth)

if n == num:

print(num, "is an isomorphic number. ")

else:print(num, "Not an isomorphic number. ")

Algorithm:The custom function is automorphic(n) and the parameter n is the number to be detected. Calculate the square of n, stored in the variable sqr num. Use a while loop with the condition that the number to be detected is n > 0. Take the remainder 10 for n and sqr num respectively to determine whether the remainder results are equal. If it's not equal, the function returns false. Divide n and sqr num by 10 and remove the last digit. Continue the while loop. After several divisible divisions, the number n to be detected is 0 and the while loop ends. The function returns true. Use the if statement to judge the result returned by the function. If the statement is true, the output of the given number is an isomorphic number. If false, the output of the given number is not an isomorphic number.

def is_automorphic(n):

sqr_num = n * n

while n:

square_remainder = sqr_num%10

number_remainder = n%10

if square_remainder != number_remainder:

return false

n //= 10

sqr_num //= 10

return true

n = 25

if is_automorphic(n):

print(n, "is an isomorphic number. ")

else:print(n, "Not an isomorphic number. ")

Algorithm:Use string slicing, combined with ternary arithmetic, to detect isomorphic numbers using a single line**.

n = 25

# n^2 = 625 '625'[-2::]= 25

print("yes" if int(str(n**2)[-len(str(n)):== n else "no")

Algorithm:Use the endswith() method to check if the string ends with the specified value.

num = 25

a = str(num)

num1 = num **2

b = str(num1)

if b.endswith(a):

print(num, "is an isomorphic number. ")

else:print(num, "Not an isomorphic number. ")

It's not easy to create an article, if you like this article, please follow, like and share it with your friends. If you have comments and suggestions, please give us feedback in the comments.

Related Pages