Check if a number is Automorphic Number

Problem Statement: Given a number, check if it is automorphic 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:

Example 1:
Input Format: N = 76
Result: Automorphic Number
Explanation: Calculating 76 * 76 gives 5776, it ends with the given number.

Input Format: 25
Result: Automorphic Number
Explanation: Calculating 25 * 25 gives 625, it ends with the given number.

Solution

Disclaimer: Don’t jump directly to the solution, try it out yourself first.

Approach

First Store the square of the given number in an integer.

Run a loop until the number becomes 0.

  1. Inside the loop check if the last digit of the number is equal to last digit of its square.
  2. If it is not equal then return false.
  3. Otherwise divide the number by 10 inorder to reduce it.
  4. Now if the loop runs till the end then it is an Automorphic number and return true.

Code:

C++ Code

#include <iostream>

using namespace std;

bool isAutomorphic(int N) {

  int sq = N * N;

  while (N > 0) {

    // Check if last digit is equal or not
    if (N % 10 != sq % 10)
      return false;

    // Reducing the number and its square
    N /= 10;
    sq /= 10;
  }

  return true;
}

int main() {
  int N = 25;
  if(isAutomorphic(N))
  cout<<"Automorphic Number"<<endl;
  else
  cout<<"Not Automorphic Number"<<endl;
  return 0;
}

Output: Automorphic Number

Time Complexity: O(N)

Space Complexity: O(1)

Java Code

class Solution {

  public static boolean isAutomorphic(int N) {
    int sq = N * N;

    while (N > 0) {

      // Check if last digit is equal or not
      if (N % 10 != sq % 10)
        return false;

      // Reducing the number and its square
      N /= 10;
      sq /= 10;
    }

    return true;
  }
  public static void main(String args[]) {
    int n = 25;
    if(isAutomorphic(n)==true)
    System.out.println("Automorphic Number");
    else
    System.out.println("Not Automorphic Number");
  }
}     

Output: Automorphic Number

Time Complexity: O(N)

Space Complexity: O(1)

Special thanks to Rushikesh Adhav for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article