1. 平方根的计算
- 使用 Babylonian method 方法(https://en.wikipedia.org/wiki/Methods_of_computing_square_roots)进行计算:
def babylonian(s, x0, n_iter):
x = x0
for _ in range(n_iter):
x = (x + s/x)/2
print(x)
return x
2. 完全平方数的判断
https://stackoverflow.com/questions/2489435/how-could-i-check-if-a-number-is-a-perfect-square
基于 Babylonian method 方法(https://en.wikipedia.org/wiki/Methods_of_computing_square_roots)
def is_square(n): if n*n == n: # 1*1 == 1 return True x = n // 2 seen = set([x]) while x*x != n: x = (x + n//x)//2 if x in seen: return False seen.add(x) return True