16 May 2024

Automorphic number in java

Given an integer input, the Objective is to check whether the square of the number ends with the same number or not.


import java.util.*;


class HelloWorld {

    public static void main(String[] args) {

        int n=sc.nextInt();

        int square=(int)Math.pow(n,2);

        System.out.print(square%10==n?"yes":"no");

    }

}

This program determines if a given integer nn satisfies the condition where the last digit of its square equals the number itself.

For example:

  • Input: n=5n = 5
    • Square = 52=255^2 = 25
    • Last digit = 55
    • Output = Yes
  • Input: n=7n = 7
    • Square = 72=497^2 = 49
    • Last digit ≠ 77
    • Output = N0

How It Works

  1. Input:
    The program reads an integer nn.

  2. Calculate the Square:
    Use Math.pow(n,2)Math.pow(n, 2) to compute the square of nn.
    Explicitly cast the result to int since Math.powMath.pow returns a double.

  3. Check the Last Digit:
    Use the modulus operator (%) to extract the last digit of the square.
    Compare this last digit with nn.

  4. Output:
    Print "Yes" if the last digit of the square equals nn, otherwise print "No."


Example Input and Output

Example 1
Input:
5
Process:

  • 52=255^2 = 25
  • Last digit = 25mod10=525 \mod 10 = 5
  • 5=55 = 5

Output:
Yes, the square of 5 ends with 5


Example 2
Input:
7
Process:

  • 72=497^2 = 49
  • Last digit = 49mod10=949 \mod 10 = 9
  • 797 \neq 9

Output:
No, the square of 7 does not end with 7


Edge Cases

  1. Single-digit Numbers:
    All single-digit numbers are directly checked for their properties.

  2. Zero:
    Input = 00, Square = 00, Output = Yes (since 00 ends with 00).

No comments:

Post a Comment