Check for Perfect Square in Java
Check for Perfect Square in Java
Here on this page, we will learn how to Check for Perfect Square in Java programming language. We are given an integer number and need to print “True” if it is, otherwise “False”.
Algorithm ( Method 1 )
- Take the floor() value square root of the number.
- Multiply the square root twice.
- We use the Boolean equal operator to verify if the product of the square root is equal to the number given.
Java Code
Run
public class Main { static boolean isPerfectSquare(int x) { if (x >= 0) { int sr = (int)Math.sqrt(x); return ((sr * sr) == x); } return false; } public static void main(String[] args) { int x = 84; if (isPerfectSquare(x)) System.out.print("True"); else System.out.print("False"); } }
Output
False
Algorithm ( Method 2 )
- In this method we use the floor and ceil function.
- If they are equal that implies the number is a perfect square.
Run
import java.io.*; public class Main{ static void checkperfectsquare(int n) { if (Math.ceil((double)Math.sqrt(n)) == Math.floor((double)Math.sqrt(n))) { System.out.print("True"); } else { System.out.print("False"); } } public static void main(String[] args) { int n = 49; checkperfectsquare(n); } }
Output
True
For similar Questions click on the given button
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
import java.util.*;
public class Max {
public static void main(String[] args){
int max =0;
Map a = new HashMap();
int arr[][] ={
{0,0,0,0},
{0,0,1,1},
{1,1,1,1},
{1,1,0,0}
};
int r = 4;
int c =4;
for(int i=0 ; i<4 ; i++){
int count =0;
for(int j=0 ; j<4 ; j++){
if(arr[i][j] ==1){
count++;
a.put(i,count);
}
}
}
for(Map.Entry op :a.entrySet()){
if(op.getValue() > max){
max = op.getValue();
}
}
for(Map.Entry op :a.entrySet()){
if(op.getValue() == max){
System.out.println(op.getKey()+1);
}
}
}
}