Java Program to check whether a number is a perfect square or not


April 15, 2022, Learn eTutorial
1159

Here we are explaining how to write a java program to check whether a number is a perfect square root or not.

How to find out the square root of a number in java?

We can find out the square root of a number by using the function Math.sqrt(). The syntax of  Math.sqrt() the function is shown below.

public static double sqrt(double x)

How to implement the java program to check whether a number is a perfect square or not?

First, we have to declare the class Square. Then declare the integer variable num. Create an object of the scanner class as sc. Read the number from the user into the variable num.Check if isPS(num) returns true or false.If it returns true then display the number as a perfect square. Else display the number is not a perfect square.

The isPs(x) function will return true if the number is a perfect square. To find out the square root of a number we can use the function Math.sqrt() . Then we will find out the closest integer of the number, using Math.floor() function. Then we will find out the difference between sr and Math.floor(sr).If the difference is equal to zero then return true.

ALGORITHM

STEP 1: Declare the class Square with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the integer variable num.

STEP 4: Check if isPS(num), if true then display the number as a perfect square.

STEP 5: Else display the number is not a perfect square.

FUNCTION  static boolean isPS(double x) 

STEP 1: Find out the square root of x by calling the function Math.sqrt(x)  into the variable sr.

STEP 2: Check sr - Math.floor(sr) equals zero then return true.

 

Java Source Code

                                          import java.util.Scanner;
public class Square {

 static boolean isPS(double x) {

  double sr = Math.sqrt(x);

  return ((sr - Math.floor(sr)) == 0);
 }

 public static void main(String[] args) {

  int num;
  Scanner sc = new Scanner(System. in );

  System.out.println("Enter the Number: ");
  num = sc.nextInt();

  if (isPS(num)) System.out.println("The Number " + num + " is a perfect square");
  else System.out.println("The Number " + num + " is not a perfect square");
 }
}
                                      

OUTPUT

Enter the Number: 25
The Number 25 is a perfect square