w3resource

Java: Test if a given number is a perfect square or not


Check Perfect Square

Write a Java program to test if a given number (positive integer) is a perfect square or not.

Input number: 3 Output: 1 2 3 8 9 4 7 6 5

Visual Presentation:

Java Basic Exercises: Test if a given number is a perfect square or not


Sample Solution:

Java Code:

// Import Scanner class from java.util package for user input
import java.util.*;

// Main class for the solution
public class Solution {
    // Main method to execute the solution
    public static void main(String[] args) {
        // Create a Scanner object for user input
        Scanner in = new Scanner(System.in);

        // Prompt the user to input a positive integer
        System.out.print("Input a positive integer: ");

        // Read the user input as an integer
        int n = in.nextInt();

        // Display the result of the is_Perfect_Square function
        System.out.print("Is the said number perfect square? " + is_Perfect_Square(n));
    }

    // Function to check if a given number is a perfect square
    public static boolean is_Perfect_Square(int n) {
        // Extract the last digit of the number
        int x = n % 10;

        // Check if the last digit is 2, 3, 7, or 8 (numbers whose squares end with these digits)
        if (x == 2 || x == 3 || x == 7 || x == 8) {
            return false;
        }

        // Iterate from 0 to half of the input number plus 1
        for (int i = 0; i <= n / 2 + 1; i++) {
            // Check if the square of the current iteration is equal to the input number
            if ((long) i * i == n) {
                return true;
            }
        }

        // If no perfect square is found, return false
        return false;
    }
} 

Sample Output:

Input a positive integer:  6
Is the said number perfect square? false 

Flowchart:

Flowchart: Java exercises: Test if a given number is a perfect square or not


For more Practice: Solve these Related Problems:

  • Write a Java program to test if a given number is a perfect cube.
  • Write a Java program to find the next perfect square that is greater than a specified number.
  • Write a Java program to count the number of perfect squares within a specified numerical range.
  • Write a Java program to determine if a number is a perfect square without using built-in square root functions.

Go to:


PREV : Generate Spiral Matrix.
NEXT : Prime Number Position.

Java Code Editor:

Company:  LinkedIn

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.