program to check whether the given number is perfect square or not in Java
Answers
import java. until. *;
//Example 1
/*To check perfect square or not*/
public class PSquare
{
public static void main()
{
Scanner sc = new Scanner(System.in);
system.out.println("Enter a number");
int a = sc. nextInt();
int b = Math. sqrt(a);
if(b%1==0)
{
System.out.in println("Perfect square ");
}
else
System.out.in println("Not a Perfect square ");
}
}
follow me
hope it helps
mark it as brainliest
Perfect Square - Java
We need to check if a number is a Perfect Square or not. The method we will use is this:
- Take User Input for a number
- Find its Square Root using Math.sqrt()
- Store this Square Root in a variable, say root
- Type cast root from double to int
- If the typecast int value is same as the double value, number is a Perfect Square
This works on the logic that for Perfect Squares, the Square Root is also an Integer. So, they have essentially no Decimal Expansion.
For example,
So, 49 is a Perfect Square.
import java.util.Scanner;
public class PerfectSquare
{
public static void main(String[] args)
{
//Creating Scanner Object
Scanner scr = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scr.nextInt(); //Taking User Input
double root = Math.sqrt(number); //Getting Square Root of number
//We typecast the root from double to int
//If the value remains same, it is a Perfect Square
//This is because for Perfect Squares, root is also an integer
if(root == (int)root)
{
System.out.println(number+" is a Perfect Square.");
}
else
{
System.out.println(number+" is Not a Perfect Square.");
}
}
}