Python algorithm-2. Complete square


Write in front

This is a study note made by bloggers who encountered a case in learning Python algorithm. The case comes from "Python Algorithm Guide-Programmer's Classic Algorithm Analysis and Implementation", the source code refers to the book.


Problem Description

Given a positive integer, judge whether it is a perfect square number.

Examples of questions

The number that satisfies the square root and the square is equal to itself is a perfect square number, such as 25 = 5² is a perfect square number.

problem solved

Given a positive integer n, the simplest method is to traverse each number from 1 to (n-1) to determine whether its square is equal to n, and the time complexity is O(n).
It can be improved slightly, and from the mean inequality, the arithmetic average (1+n)/2 ≥ √n, so the traversal range can be reduced from 1 to (1+n)/2, but the time complexity of this calculation is still Is O(n).
In "Data Structure", I have learned the method of half-and-half search, which reduces the search range by half until the time complexity is O(n)=log2(N). Apply this idea to this problem.
Let the lower boundary low of the initial exploration range be 1, the upper boundary high be n, and the middle value min = (1+n)/2, compare the size of min² and n. If the former is smaller, it means that the value you are looking for is larger than mid. To the right of, modify the lower boundary of the exploration range low to mid; otherwise, modify the value of the upper boundary to high, and repeat the above operation until the two boundaries are adjacent integers.
Take the final lower boundary as the result ans, if ans² is smaller than n, take the result of the upper boundary as ans, and compare whether ans² and n are equal.
Importing the math library and calling sqrt() can also implement the corresponding functions.
Based on the above analysis, the code is as follows:

import  math

class Solution:
    '''不调用外部函数'''
    def isSquare1(self,n):
        low = 1
        high = n
        while(high - low > 1):
            mid = int((high + low) / 2)
            print("low = ",low,"mid = ",mid,"high = ",high,'\n')
            if(mid * mid <= n):
                low = mid
            else:
                high = mid
        print("low = ",low,"mid = ",mid,"high = ",high,'\n')
        ans = low
        if(low * low < n):
            ans = high
        return ans * ans == n
    
    def isSquare2(self,n):
        return (int(math.sqrt(n))) ** 2 == n
    
if __name__ == "__main__":
    print("输入值:")
    n = int(input())
    print("值:",n)
    solution = Solution()
    print("1.是否为完全平方数:",solution.isSquare1(n))
    print("2.是否为完全平方数:",solution.isSquare2(n))

The test results are printed as follows:
1
2


to sum up

This question is relatively simple, but also reviewed the search by half. For some algorithms with a large search value and a huge range, the time complexity of the algorithm can be reduced by using the binary search.

Guess you like

Origin blog.csdn.net/weixin_47585015/article/details/110959176