# C#LeetCode刷题之#367-有效的完全平方数（Valid Perfect Square）

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Input: 16

Output: true

Input: 14

Output: false

```public class Program {

public static void Main(string[] args) {
var n = 25;
var res = IsPerfectSquare(n);
Console.WriteLine(res);

n = 17;
res = IsPerfectSquare2(n);
Console.WriteLine(res);

n = 256;
res = IsPerfectSquare3(n);
Console.WriteLine(res);

}

private static bool IsPerfectSquare(int num) {
//耍赖
var squard = Math.Sqrt(num);
return (int)squard - squard == 0;
//return Math.Sqrt(num) % 1 == 0;
}

private static bool IsPerfectSquare2(int num) {
//完全平方数的差都为奇数，即1，3，5，7，9...
//完全平方数是n个奇数的和
for(var i = 1; num > 0; i += 2) {
num -= i;
}
return num == 0;
}

private static bool IsPerfectSquare3(int num) {
//二分逼近，最后收敛于sqrt(x)
long res = num;
while(res * res > num) {
res = (res + num / res) / 2;
}
return (int)(res * res) == num;
}

}```

```True
False
True```

IsPerfectSquare 的时间复杂度依赖于运行库的实现，IsPerfectSquare2 的时间复杂度为：  ，IsPerfectSquare3 的时间复杂度为：