In this tutorial, we will write a java program to check if a given number is a perfect square or not. Before that, you should have knowledge of the following topic in Java.
We will look at two java perfect square programs:
- With sqrt() function
- Without sqrt() funciton
Both of the programs below take the number as user input and process it. The first program uses the math function sqrt() to check for perfect square and the second program uses if..else statement to check.
In this java program, both programs have a user-defined boolean function that returns true or false to the main function.
Using sqrt() function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.util.Scanner; public class Main { public static void main(String[] args) { int num; boolean result = false; Scanner scan = new Scanner(System.in); System.out.print("Enter the number: "); num = scan.nextInt(); result = isPerfectSquare(num); // check the returned result if (result) System.out.println(num + " is a Perfect Square"); else System.out.println(num + " is NOT a Perfect Square"); } //user-defined function public static boolean isPerfectSquare(int num) { double root = Math.sqrt(num); return (root - Math.floor(root) == 0); } } |
Output:
Enter the number: 16
16 is a Perfect Square
Java Program to check for Perfect Square without using sqrt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.util.Scanner; public class Main { public static void main(String[] args) { int num; Scanner scan = new Scanner(System.in); System.out.print("Enter the number: "); num = scan.nextInt(); // check the result with condition if (isPerfectSquare(num)) System.out.println(num + " is a Perfect Square"); else System.out.println(num + " is NOT a Perfect Square"); } //user-defined function public static boolean isPerfectSquare(int num) { for (int i = 1; i * i <= num; i++) { if ((num % i == 0) && (num / i == i)) return true; } return false; } } |
Output:
Enter the number: 25
25 is a Perfect Square
Enter the number: 21
21 is NOT a Perfect Square