Write a program to print all the automorphic numbers from 1 to 1000 using following
functions.
void automorphic(int n) where the function receives series of numbers from 1 to
1000 from the function call statement and print it on the screen if found automorphic.
(Automorphic number is one which is found in the square of its value in the last
digits) for example : 25 is an automorphic as it is available in its square (625).
void main():Generates series of numbers from 1 to 1000 and passes it to method void automorphic(int n).
Answers
1. Find the square of the number.
2. Convert both the numbers to string.
3. Use endsWith() function to check whether the square of the number ends with the number or not!
public class Automorphic{
void automorphic(int n){
String num=String.valueOf(n);
String sqr=String.valueOf(n * n);
if(sqr.endsWith(num))
System.out.print(n+" ");
}
public static void main(String s[]){
Automorphic obj=new Automorphic();
System.out.println("Automorphic Numbers from 1 to 1000 are as follows - ");
for(int i=1;i<1001;)
obj.automorphic(i++);
}
}
Automorphic Numbers from 1 to 1000 are as follows -
1 5 6 25 76 376 625
See attachment for verification.
Answer:
public class Main
{
void automorphic(int n)
{
String s,st;
s=Integer.toString(n);
st=Integer.toString(n*n);
if(st.endsWith(s))
System.out.print(s+" ");
}
public static void main(String args[])
{
Main ob=new Main();
System.out.println("Automorphic numbers are:");
for(int i=1;i<=1000;i++)
{
ob.automorphic(i);
}
}
}