An Automorphic number is a number whose square ends with the same digits as the original number. E.g – 5, 6, 76 etc.
Steps to Check Automorphic Number in C:
- Take a number as input (
num
). - Count number of digits in the number (
n
) - Find Square of the number (
sqr
). - Extract last
n
digits from thesqr
(last
). - If
last == num
then number is Automorphic else not.
Here is the implementation of the steps in C.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int num, sqr, temp, last;
int n =0;
printf("Enter a number \n");
scanf("%d",&num);
sqr = num*num; //calculating square of num
temp = num;
//Counting number of digits
while(temp>0){
n++;
temp = temp/10;
}
//Extracting last n digits
int den = floor(pow(10,n));
last = sqr % den;
if(last == num)
printf("Automorphic number \n");
else
printf("Not Automorphic \n");
return 0;
}
Output
Find all Automorphic Numbers in the Interval
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void automorphic(int num){
int sqr, temp, last;
int n =0;
sqr = num*num; //calculating square of num
temp = num;
//Counting number of digits
while(temp>0){
n++;
temp = temp/10;
}
//Extracting last n digits
int den = floor(pow(10,n));
last = sqr % den;
if(last == num)
printf("%d \n",num);
}
int main()
{
int upper, lower, i;
printf("Enter lower interval \n");
scanf("%d",&lower);
printf("Enter upper interval \n");
scanf("%d",&upper);
printf("-------------------------- \n");
for(i=lower; i<upper; i++){
automorphic(i);
}
return 0;
}
Output
In this tutorial, we have learned to check automorphic in C.