Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Exercises: 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

Pictorial Presentation:

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

Sample Solution:

Java Code:

import java.util.*;
public class Solution {
 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  System.out.print("Input a positive integer: ");
  int n = in .nextInt();
  System.out.print("Is the said number perfect square? " + is_Perfect_Square(n));
 }

 public static boolean is_Perfect_Square(int n) {
  int x = n % 10;
  if (x == 2 || x == 3 || x == 7 || x == 8) {
   return false;
  }
  for (int i = 0; i <= n / 2 + 1; i++) {
   if ((long) i * i == n) {
    return true;
   }
  }
  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.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe