C++ Program to check whether a number is an Automorphic number or not

Program to check whether a number is an Automorphic number or not

Here we will discuss how to check whether a number is an Automorphic number or not using C++ programming language.

An automorphic number is a number in which the last digits of the square of the number is equal to the number itself.

To check for Automorphic number, first find the square of the number. Then compare the last digits of the square by the number digit by digit and then are equal then it’s an Automorphic number else not.

Example: 25
Square of 25 = 625
As we can see the last digits of square equals to the number, so 25 is an Automorphic number.

Program to check for automorphic number

Working

Let’s see how the code works:

  • User gives an input(number).
  • Input is stored in an int type variable say num.
  • The square of num is found and stored in another variable say sq
  • num is stored in another variable called store for future use.
  • A loop is started
    • If the last digit of the num and sq are not equal then turn flag = 1 and break the loop

        if(num%10!=sq%10)

                   flag=1;

           break;

    • Divide both num and sq by 10.

        num=num/10;

        sq=sq/10;

    • The loop will run till num is greater than 0. 

while(num>0)

  • If flag is equal to 1 then the number is not an automorphic number.
  • Otherwise the number is an Automorphic number.

C++ Code

//C++ Program
//Automorphic number or not
#include<iostream>
using namespace std;
//main program
int main()
{
int num,flag=0;
cout<<"Enter a positive number to check: ";
//user input
cin>>num;
int sq= num*num;
int store=num;
//check for automorphic number
while(num>0)
{
if(num%10!=sq%10)
{
flag=1;
break;
}
num=num/10;
sq=sq/10;
}
if(flag==1)
cout<<store<<" is not an Automorphic number.";
else
cout<<store<<" is an Automorphic number.";
return 0;
}

Output

Enter a positive number to check: 25
25 is an Automorphic number.

Please Login/Signup to comment