How to check whether number is perfect square or not in Java

4 Answers

0 votes
// When a square root is a whole number, then the number is a perfect square number

public class MyClass {
    private static boolean isPerfectSquare(int number) {
    	double d_sqrt = Math.sqrt((double)number);
    	int n = (int)d_sqrt;
    
    	if (n == d_sqrt) {
    		return true;
    	}
    	else {
    		return false;
    	}
    }
    public static void main(String args[]) {
     	int num = 81;

	    if (isPerfectSquare(num) != false) {
		    System.out.print(num + " is a perfect square");
	    }
	    else {
		    System.out.print(num + " is not a perfect square");
	    }
    }
}








/*
run:
  
81 is a perfect square
  
*/

 



answered May 13, 2023 by avibootz
0 votes
// When a square root is a whole number, then the number is a perfect square number

public class MyClass {
    private static boolean isPerfectSquare(int number) {
    	if (number >= 0) {
            double d_sqrt = Math.sqrt((double)number);
              
            return d_sqrt * d_sqrt == number;
        }
 
        return false;
    }
    public static void main(String args[]) {
     	int num = 81;

	    if (isPerfectSquare(num) != false) {
		    System.out.print(num + " is a perfect square");
	    }
	    else {
		    System.out.print(num + " is not a perfect square");
	    }
    }
}








/*
run:
  
81 is a perfect square
  
*/

 



answered May 13, 2023 by avibootz
0 votes
// When a square root is a whole number, then the number is a perfect square number

public class MyClass {
    private static boolean isPerfectSquare(int number) {
        double d_sqrt = Math.sqrt((double)number);
              
        if ((int)Math.pow((int)(d_sqrt + 0.5), 2) == number)
            return true;
        else
            return false;
    }
    public static void main(String args[]) {
     	int num = 81;

	    if (isPerfectSquare(num) != false) {
		    System.out.print(num + " is a perfect square");
	    }
	    else {
		    System.out.print(num + " is not a perfect square");
	    }
    }
}








/*
run:
  
81 is a perfect square
  
*/

 



answered May 13, 2023 by avibootz
0 votes
// When a square root is a whole number, then the number is a perfect square number
 
public class MyClass {
    private static boolean isPerfectSquare(int number) {
        double sq = Math.sqrt(number); 
        
       return ((sq - Math.floor(sq)) == 0); 
    }
    public static void main(String args[]) {
        int num = 81;
 
        if (isPerfectSquare(num) != false) {
            System.out.print(num + " is a perfect square");
        }
        else {
            System.out.print(num + " is not a perfect square");
        }
    }
}
 
 
 
/*
run:
   
81 is a perfect square
   
*/

 

 



answered Sep 16, 2025 by avibootz
...