Check squareRoot of integer without using sqrt().
Write a function named isSquare that returns 1 if its integer is a square of some integer, otherwise it returns 0. Your function must not use any function or method (e.g.sqrt) that comes with a runtime library or class library!
The signature of the functions:
int isSquare(int n)
Example:
If n is |
return |
reason |
4 |
1 |
Because 4=2*2 |
25 |
1 |
Because 25=5*5 |
-4 |
0 |
Because there is no integer that when squared equals -4(note,-2 squared is 4 not-4) |
8 |
0 |
Because the square root of 8 is not an integer |
0 |
1 |
Because 0=0*0 |
Solution:
using System;
namespace SquareRoot
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter The Number:");
string p = Console.ReadLine().Trim();
int n = Int32.Parse(p);
n = isSquare(n);
Console.Write(n);
}
static int isSquare(int n)
{
bool isroot = false;
if (n == 0)
{
return 1;
}
else if (n < 0)
{
return 0;
}
else
{
for (int i = 1; i < n; i++)
{
int a = i * i;
if (a == n)
{
isroot = true;
}
}
if (isroot)
{
return 1;
}
else
{
return 0;
}
}
}
}
}
Output: