Computer Applications

Write a program to input a number and check whether the number is an automorphic number or not.

An automorphic number is a number whose square "ends" in the same digits as the number itself.

e.g. 52 = 25, 62 = 36, 762 = 5776

Java

Java Iterative Stmts

10 Likes

Answer

import java.util.Scanner;

public class KboatAutomorphic
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = in.nextInt();
        int numCopy = num;
        int sq = num * num;
        int d = 0;

        /*
         * Count the number of 
         * digits in num
         */
        while(num > 0) {
            d++;
            num /= 10;
        }

        /*
         * Extract the last d digits
         * from square of num
         */
        int ld = (int)(sq % Math.pow(10, d));

        if (ld == numCopy)
            System.out.println(numCopy + " is automorphic");
        else
            System.out.println(numCopy + " is not automorphic");
    }
}

Output

Answered By

6 Likes


Related Questions