【一题多解】平方根的计算及完全平方数的判断

1. 平方根的计算

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

猜你喜欢

转载自blog.csdn.net/lanchunhui/article/details/81073406