Calculate Nth root with integer arithmetic

前端 未结 6 929
梦如初夏
梦如初夏 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:24

    Algorithm more simple in VBA.

    Public Function RootNth(radicand As Double, degree As Long) As Double
       Dim countDigits As Long, digit As Long, potency As Double
       Dim minDigit As Long, maxDigit As Long, partialRadicand As String
       Dim totalRadicand As String, remainder As Double
    
      radicand = Int(radicand)
      degree = Abs(degree)
      RootNth = 0
      partialRadicand = ""
      totalRadicand = CStr(radicand)
      countDigits = Len(totalRadicand) Mod degree
      countDigits = IIf(countDigits = 0, degree, countDigits)
      Do While totalRadicand <> ""
         partialRadicand = partialRadicand + Left(totalRadicand, countDigits)
         totalRadicand = Mid(totalRadicand, countDigits + 1)
         countDigits = degree
         minDigit = 0
         maxDigit = 9
         Do While minDigit <= maxDigit
            digit = Int((minDigit + maxDigit) / 2)
            potency = (RootNth * 10 + digit) ^ degree
            If potency = Val(partialRadicand) Then
               maxDigit = digit
               Exit Do
            End If
            If potency < Val(partialRadicand) Then
               minDigit = digit + 1
            Else
               maxDigit = digit - 1
            End If
         Loop
         RootNth = RootNth * 10 + maxDigit
      Loop
       End Function
    

提交回复
热议问题