import java.util.Scanner;
class Automorphic
{
int l, u; // lower and upper limits of the range
int count; // frequency of automorphic numbers in the range
// parameterised constructor
Automorphic(int l, int u)
{
this.l = l;
this.u = u;
count = 0;
}
// returns true if n is an automorphic number
boolean check(int n)
{
long sq = (long) n * n;
String ns = Integer.toString(n);
String sqs = Long.toString(sq);
return sqs.endsWith(ns);
}
// checks every number in the range, displays the automorphic ones and their frequency
void list()
{
System.out.println("List of Automorphic numbers from " + l + " to " + u + " :");
System.out.println("Number\tSquare");
count = 0;
for (int i = l; i <= u; i++)
{
if (check(i))
{
long sq = (long) i * i;
System.out.println(i + "\t" + sq);
count++;
}
}
System.out.println("Frequency of Automorphic numbers between " + l + " to " + u + " : " + count);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the lower limit of the range->");
int l = sc.nextInt();
System.out.print("Enter the upper limit of the range->");
int u = sc.nextInt();
Automorphic ob = new Automorphic(l, u);
ob.list();
}
}
Explanation: check(n) compares the string form of n's square against the string form of n itself - n is automorphic exactly when its square's string ends with n's own digits (this avoids any issue with leading digits and works for any size square by using long). list() calls check() on every number from l to u, prints the number and its square for each automorphic one, and counts them. Tested (run for real) with l=1, u=1000: the program printed the numbers 1, 5, 6, 25, 76, 376, 625 with their squares and "Frequency of Automorphic numbers between 1 to 1000 : 7", matching the sample output exactly.