Python 3 complete square case

Time:2021-10-12

subject

An integer is a complete square number after adding 100, and a complete square number after adding 168. What is the number?

Program analysis

Because 168 is too small for exponential explosion, mathematical analysis can be omitted directly and the upper limit can be obtained by the most simple method:

?
1
2
3
4
n=0
while (n+1)**2-n*n<=168:
 n+=1
print(n+1)

Supplement: a method of realizing “effective complete square number” in Python

For a positive integer num, write a function to judge whether it is a complete square number. If yes, it returns true, not false

Note: do not use any embedded functions, such as sqrt

Example 1

?
1
2
3
4
5
Input: 16
Output: true
Example 2:
Input: 14
Output: false

1: Dichotomy

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def isPerfectSquare(self, num):
  """
  :type num: int
  :rtype: bool
  """
  low = 1
  high = num
  while low < high:
   mid = (low + high) // 2
   if mid * mid == num:
    return True
   elif mid * mid < num:
    low = mid + 1
   else:
    high = mid - 1
  return low * low == num

The above is my personal experience. I hope I can give you a reference, and I hope you can support developepper. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.