代码之家  ›  专栏  ›  技术社区  ›  RAGHHURAAMM

scala:bigint平方根的函数

  •  1
  • RAGHHURAAMM  · 技术社区  · 6 年前

    shiftRight(5), BigInt("8") and shiftRight(1)

       def sqt(n:BigInt):BigInt = {
          var a = BigInt(1)
          var b = (n>>5)+BigInt(8)
          while((b-a) >= 0) {
              var mid:BigInt = (a+b)>>1
              if(mid*mid-n> 0) b = mid-1
              else a = mid+1
             }
          a-1
       }
    

    我的观点是:

    1. shiftRight(5), shiftRight(1) and 8

    sqt

    scala> sqt(BigInt("19928937494873929279191794189"))
    res9: BigInt = 141169888768369
    
    scala> res9*res9
    res10: scala.math.BigInt = 19928937494873675935734920161
    
    scala> sqt(res10)
    res11: BigInt = 141169888768369
    
    scala>
    

    shiftRight(5) means divide by 2^5 ie.by 32 in decimal 等等……但为什么在轮班后在这里加8?为什么是5班?作为第一个猜测?

    2 回复  |  直到 6 年前
        1
  •  4
  •   jwvh    6 年前

    here

    1. a n
    2. b
    3. mid
    4. a-1

    var b = n

    (n>>5)+8 (n>>7)+12

    def sqt(n:BigInt) :BigDecimal = {
      val d = BigDecimal(n)
      var a = BigDecimal(1.0)
      var b = d
      while(b-a >= 0) {
        val mid = (a+b)/2
        if (mid*mid-d > 0) b = mid-0.0001  //adjust down
        else               a = mid+0.0001  //adjust up
      }
      b
    }
    

        2
  •  0
  •   Alexey Romanov    6 年前

    BigInt BigDecimal Double

    n n/32 + 8 >= sqrt(n) sqrt a <= sqrt(n) <= b n == 0