Does Anybody Knows the Logic To Find Out a Number is Perfect Square or not ? (Other than Newtons Method or Synthetic Division Method)
For Eg:- 4, 16, 36, 64 are Perfect Squares.
I will be giving the input as 441, logic should say whether its a Perfect Square or not.
It was a question asked in Amazon Interview.
Loading

VulpesPosted Jun 30, 2011, 9:43 AM
raghu vPosted Jun 30, 2011, 9:02 AM
try the follwoing code
static void Main(string[] args)
{
if (IsSquare(441))
{
Console.Write("Perfect");
}
else
{
Console.Write("Perfect");
}
Console.Read();
}
static bool IsSquare(int n)
{
int i = 1;
for (; ; )
{
if (n < 0)
return false;
if (n == 0)
return true;
n -= i;
i += 2;
}
}
Manikavelu VelayuthamPosted Jun 30, 2011, 8:52 AM
I already found a way to find out, But I want to see any other optimal way to find it.
Dorababu MekaPosted Jun 30, 2011, 8:39 AM
Manikavelu VelayuthamPosted Jun 30, 2011, 8:34 AM
Without using any In Built functions.
raghu vPosted Jun 30, 2011, 8:29 AM
try this
double result = Math.Sqrt(numberToCheck);
bool isSquare = result%1 == 0;
to be more clear
double result = Math.Sqrt(16);
bool isSquare = result % 1 == 0;
if (isSquare)
{
Console.Write("Perfect");
}
Console.Read();
some thing like abv