Write a java program to input two unequal positive numbers and check whether they are perfect square or not.
Answers
Answer:
Java Example to check if a number is perfect square
In this program, we have created a user-defined method checkPerfectSquare() that takes a number as an argument and returns true if the number is perfect square else it returns false.
In the user defined method we are using two methods of the Math class, sqrt() method and floor() method. The Math.sqrt() method finds the square root of the given number and the floor() method finds the closest integer of the square root value returned by sqrt() method. Later we have calculated the difference between these two to check whether the difference is zero or non-zero. For a perfect square number this difference should be zero as the square root of perfect square number is integer itself.
package com.beginnersbook;
import java.util.Scanner;
class JavaExample {
static boolean checkPerfectSquare(double x)
{
// finding the square root of given number
double sq = Math.sqrt(x);
/* Math.floor() returns closest integer value, for
* example Math.floor of 984.1 is 984, so if the value
* of sq is non integer than the below expression would
* be non-zero.
*/
return ((sq - Math.floor(sq)) == 0);
}
public static void main(String[] args)
{
System.out.print("Enter any number:");
Scanner scanner = new Scanner(System.in);
double num = scanner.nextDouble();
scanner.close();
if (checkPerfectSquare(num))
System.out.print(num+ " is a perfect square number");
else
System.out.print(num+ " is not a perfect square number");
}
}
package com.company;
/* Write a program to accept a number and check whether the number is a perfect square or not.
Sample Input=49
Sample Output= A perfect square.
*/
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println("Enter a Number:");
double n = sc.nextDouble();
double n2 = Math.sqrt(n);
if (n2%1==0) {
System.out.println("The entered number is a perfect square");
}
else {
System.out.println("The entered number is not a perfect square");
}
}
}