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


VulpesRank #55 · 29.2K reputationPosted Jun 30, 2011, 5:43 AM EDT
raghu v52 reputationPosted Jun 30, 2011, 4:29 AM EDT
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
Manikavelu VelayuthamRank #413 · 6K reputationPosted Jun 30, 2011, 4:34 AM EDT
Without using any In Built functions.
Dorababu MekaRank #457 · 5.5K reputationPosted Jun 30, 2011, 4:39 AM EDT
Manikavelu VelayuthamRank #413 · 6K reputationPosted Jun 30, 2011, 4:52 AM EDT
I already found a way to find out, But I want to see any other optimal way to find it.
raghu v52 reputationPosted Jun 30, 2011, 5:02 AM EDT
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;
}
}