Calculate Nth root with integer arithmetic

前端 未结 6 930
梦如初夏
梦如初夏 2020-12-16 15:12

There are a couple of ways to find integer square roots using only integer arithmetic. For example this one. It makes for interesting reading and also a very interesting the

6条回答
  •  无人及你
    2020-12-16 15:31

    One easy solution is to use the binary search.

    Assume we are finding nth root of x.

    Function GetRange(x,n):
        y=1
        While y^n < x:
            y*2
        return (y/2,y)
    
    Function BinSearch(a,b,x,):
        if a == b+1:
            if x-a^n < b^n - x:
               return a
            else:
               return b
        c = (a+b)/2
        if n< c^n:
            return BinSearch(a,c,x,n)
        else:
            return BinSearch(c,b,x,n)
    
    a,b = GetRange(x,n)
    print BinSearch(a,b,x,n)
    

    ===Faster Version===

    Function BinSearch(a,b,x,):
        w1 = x-a^n
        w2 = b^n - x
        if a <= b+1:
            if w1 < w2:
               return a
            else:
               return b
        c = (w2*a+w1*b)/(w1+w2)
        if n< c^n:
            return BinSearch(a,c,x,n)
        else:
            return BinSearch(c,b,x,n)
    

提交回复
热议问题