Automorphic Number using Java


What is an Automorphic Number?

If the square of a number ends with the number itself, it is considered to be automorphic.

For Example:
25 is an automorphic number, as the square of 25 = 625 (ends with 25).
 5^2 = 25
 6^2 = 36
 76^2 = 5776
Sequence of automorphic numbers: 1, 5, 6, 25, 76, 376, ..

Write a program to verify or check whether a given number is automorphic or not using Java

Write a program to verify or check whether a given number is automorphic or not using Java

import java.util.Scanner; public class AutomorphicNumber { public static void main(String[] args) { Scanner in = new Scanner(; System.out.println( "*** Automorphic number ***\n"); // Enter a number : long num = in.nextLong(); long sqNum = num*num; String strNum = Long.toString(num); String square = Long.toString(sqNum); String result = ( square.endsWith(strNum) )? "Automorphic":"Not Automorphic"; System.out.println(" Number " +num+" is "+result); } }

Write a program to find all the automorphic numbers in a range

/* Description: The code finds all automorphic numbers in given range [1-N] */ import java.math.BigInteger; import java.util.Comparator; import java.util.HashSet; import java.util.Scanner; public class AutomorphicNumbers{ public static void main(String...arg){ try { String s=new Scanner( nextLine(); BigInteger N=new BigInteger(s), TEN=BigInteger.valueOf(10); HashSet<String> set=new HashSet< String>(); int j=1; String s1="", s2=""; for(int i=0; i<10; i++){ boolean find=false; BigInteger s1B=new BigInteger (i+s1), s2B=new BigInteger(i+s2); if(N.compareTo(s1B)<0 && N. compareTo(s2B)<0) break; if((""+s1B.pow(2)).endsWith(i+s1)){ s1=i+s1; find=true; } if((""+s2B.pow(2)).endsWith(i+s2)){ s1=i+s2; s1B=s2B; find=true; } if(find){ if(N.compareTo(s1B)>=0&&!(j==1&&i==0)) set.add(s1); if(!(j==1&&i<2)){ s2=((TEN.pow(j-1)). multiply(TEN)).add(BigInteger.ONE).subtract(s1B).toString(); if (N.compareTo(new BigInteger(s2))>=0) set.add(s2); while(s2.length()<j) s2=0+s2; i=0; j++; }// end if(!(j==1&&o<2)) }// end if(find) }// end for // display result: System.out.printf("In range [1-%s] the automorphic numbers are:%n", s); comparing(String::length).thenComparing(String::compareTo)).forEach(System.out::println); } catch(NumberFormatException e){ System.out.println("Wrong input. Try again!"); } } }

Solution Worked 0 UpvotesUpvote


Solution Didn't Worked 0 DownvotesDownvote


Get Programming Help

Play 2048 Game Online

Search Tags

    Automorphic Number Program in Java

    Java program for Automorphic number

    Java Program to check for Automorphic Number