wap accept an integer and test wheater it is prefect square or not
Answers
Answer:
import math
a = int(input("Enter an integer: "))
if(math.sqrt(a) % 1 != 0):
print(a, "is not a perfect square")
else:
print(a, "is a perfect square.")
Question:-
Write a program to accept an integer and test whether it is a perfect square or not.
Code:-
Here is your code, written in Java.
import java.util.*;
class Perfect_Square
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer.");
int n=sc.nextInt();
double s=Math.sqrt(n);
if(s==(int)s)
System.out.println("Number is a perfect square. ");
else
System.out.println("Number is not a perfect square. ");
}
}
How it works?
Square root of a perfect square integer is always an integer. Consider a number say 49
n=49
s=7.0
(int)s=7
So, 7.0==7 which is true.
So, it is a perfect square.
Again, consider a number, say 3.
n=3
s=1.732...(square root of 3)
(int)s=1
But, 1.732==1 is false.
So, 3 is not a perfect square.
In this way, the program works.