w3resource

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

Java Basic: Exercise-197 with Solution

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

Java Code Editor:

Company:  LinkedIn

Contribute your code and comments through Disqus.

Previous: Write a Java program to create a spiral array of n * n sizes from a given integer n.
Next: Write a Java program to get the position of a given prime number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/basic/java-basic-exercise-197.php