Automorphic Number

easy Number Problems

Problem

An automorphic number is a number whose square ends with the number itself. Example: 25 squared is 625, and 625 ends with 25. Read a non-negative integer and print true if it is automorphic, otherwise false.

Constraints

  • 0 <= n <= 10^7 (the square must fit in a safe number)

Examples

Input

25

Output

true

Input

7

Output

false

Solutions

Best approachTime O(d)Space O(1)

The last d digits of a number x are x % 10^d. We take the last d digits of the square and compare them with the number.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Check if a number is automorphic.
 * Input   : One integer.
 * Output  : true or false.
 * Approach: Compare the last digits of the square with the number.
 * Time    : O(d)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method receives a number and returns true if the number is automorphic.
    static boolean isAutomorphic(long number) {
        // Step 1: Negative numbers are not checked.
        if (number < 0) {
            return false;
        }

        // Step 2: Calculate the square of the number. Example: 25 * 25 = 625.
        long square = number * number;

        // Step 3: Find 10 to the power of the digit count. Example: 25 has 2 digits, so power = 100.
        long power = 10;
        while (power <= number) {
            power = power * 10;
        }

        // Step 4: Take the last digits of the square with the remainder. Example: 625 % 100 = 25.
        // The number is automorphic if these digits are equal to the number.
        return square % power == number;
    }

    public static void main(String[] args) {
        long number = new Scanner(System.in).nextLong();
        System.out.println(isAutomorphic(number));
    }
}
Hints (2)
  1. How can you get the last 2 digits of 625?
  2. How many digits does the number have?