-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidPerfectSquare.java
More file actions
42 lines (40 loc) · 975 Bytes
/
ValidPerfectSquare.java
File metadata and controls
42 lines (40 loc) · 975 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package easy;
/**
* ClassName: ValidPerfectSquare.java
* Author: chenyiAlone
* Create Time: 2019/7/17 22:53
* Description: No.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.
*
* Example 1:
*
* Input: 16
* Output: true
* Example 2:
*
* Input: 14
* Output: false
*
*
*/
public class ValidPerfectSquare {
public boolean isPerfectSquare(int num) {
// f(x) = f(x0) + 2x * (x - x0)
// f(x0) + 2x * (x - x0) = 0;
// x0^2 + 2 * x^2 - 2 x* x0 = 0;
for (long x = 100000; x >= 0; ) {
double newn = x - ((x * x - num) / (2.0 * x));
int t = (int)newn;
if (t * t == num) return true;
if (Math.abs(x - t) <= 1) return false;
x = t;
}
return false;
}
}