ISC practicals – Program to print all **automorphic** numbers between 1 and n, where n is a number given by the user.

In mathematics an **automorphic** number is a number whose square “ends” in the same digits as the number itself. For example,

5^{2} = 25,

6^{2} = 36,

76^{2} = 5776,

376^{2} = 141376,and

890625^{2} = 793212890625,

so 5, 6, 76 and 890625 are all **automorphic** numbers.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import java.util.*; public class Automorphic { int count(int n) //To count and return the number of digits { int c = 0; while(n>0) { n = n/10; c++; } return c; } boolean isAutomorphic(int n) { /*Extracting the last 'x' digits from the square of n where 'x' is the number of digits in n by finding the remainder when the square of n is divided by 10 to the power x*/ int sq = n*n, c = count(n); if(sq%(int)Math.pow(10, c)==n) return true; return false; } void print(int n) { int i; for(i = 1; i<=n ; i++) { if(isAutomorphic(i)) //Calling the function System.out.println(i); } } public static void main() { Scanner sc = new Scanner(System.in); int n; System.out.println("Enter the limit: "); n = sc.nextInt(); Automorphic obj = new Automorphic(); //Creating object System.out.println("The automorphic numbers between 1 and "+n+" are: "); obj.print(n); //Calling print function } } |

Output:

## Leave a Reply