VOOZH about

URL: https://www.geeksforgeeks.org/dsa/automorphic-number/

⇱ Automorphic Number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Automorphic Number

Last Updated : 20 Jan, 2025

An automorphic number is a number whose square ends in the same digits as the number itself. A number n is called automorphic if:

n2 (mod  10d) = n

where d is the number of digits in n.

Examples:

  • n = 5:
    • n2 = 25
    • Last digit of 25 is 5, so 5 is automorphic.
  • n = 76:
    • n2 = 5776
    • Last two digits of 5776 are 76, so 76 is automorphic.
  • n = 6:
    • n2 = 36
    • Last digit of 36 is 6, so 6 is automorphic.
  • n = 25:
    • n2 = 625
    • Last two digits of 625 are 25, so 25 is automorphic.

Given a number N, the task is to check whether the number is an Automorphic number or not. A number is called an Automorphic number if and only if its square ends in the same digits as the number itself.

Examples :

Input  : N = 76 
Output : Automorphic
Explanation: As 76*76 = 5776

Input  : N = 25
Output : Automorphic
As 25*25 = 625

Input : N = 7
Output : Not Automorphic
As 7*7 = 49

Approach:

  • Store the square of given number.
  • Loop until N becomes 0 as we have to match all digits with its square.
    • Check if (n%10 == sq%10) i.e. last digit of number = last digit of square or not
      • if not equal, return false.
      • Otherwise, continue i.e. reduce the number and square i.e. n = n/10 and sq = sq/10;
  • Return true if all digits matched.

Below is the implementation of the above approach: 


Output
Automorphic

Time Complexity: O(log10N)
Auxiliary Space: O(1)

Another Approach to Solve the Problem

  1. Do first check if number is negative then make it positive.
  2. Store the square of number.
  3. Find the count of the digit of the number sothat you can find the count of digit of last number of the square of the number equal to the number i.e it doesn't mean if the count of digit of last number of square is equal to the number will be equal to each other.
  4. And after counting the digit of the number perform : -  squareNum%power(10, count)
  5. Finally check the last number of square of number is equal to number or not.

Let's see the implementation as explained for above approach : -


Output
Not Automorphic

Time Complexity: - O(log10N), where N is the given number.
Auxiliary Space:- O(1)


Comment
Article Tags:
Article Tags: