topic:
Title link: https://leetcode-cn.com/problems/valid-perfect-square/
Problem-solving ideas:
Method 1: Dichotomy
Find from the half of num, then find the middle number every half
Method 2: Newton iteration
As long as it is a continuous function, and find one of the points that meet the requirements, in most cases, you can use Newton iteration
For this problem, the function expression can be understood as:
Where x is the value we want to request and num is the value entered by the program
The iterative idea of Newton's method is as follows:
- Pick a value to start iteration
- Calculating the tangent slope at
- Find the slope , and the straight line passing through the point , the x coordinate of the intersection point with the x axis , that is, find the solution to the equation:
- Represents the function of the left and right image translation units, high school (middle school?) Knowledge, plus the left and right cut, so that the purpose of the function when the image , the linear function
- Represents the slope of the tangent equation
- For the required value this time, the converted expression is:
- For this problem ,, bring the above formula to get:
- Use to continue iterating until you find a solution that makes the original formula
Borrowing the wiki animation, the whole process is as follows:
Code:
method one:
class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num < 2:
return True
left, right = 0, num // 2
while left <= right:
mid = (left + right) // 2
if mid == 0:
left = mid + 1
continue
tmp = num // mid
mod = num % mid
if tmp == mid and mod == 0:
return True
elif tmp > mid:
left = mid + 1
else:
right = mid - 1
return False
Method Two:
class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num < 2:
return True
x = num // 2
while x * x > num:
x = (x + num // x) // 2
return x * x == num