Calculate Nth root with integer arithmetic

前端 未结 6 931
梦如初夏
梦如初夏 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条回答
  •  猫巷女王i
    2020-12-16 15:29

    I made the algorithm in VBA in Excel. For now it only calculates roots of integers. It is easy to implement the decimals as well.

    Just copy and paste the code into an EXCEL module and type the name of the function into some cell, passing the parameters.

    Public Function RootShift(ByVal radicand As Double, degree As Long, Optional ByRef remainder As Double = 0) As Double
    
       Dim fullRadicand As String, partialRadicand As String, missingZeroes As Long, digit As Long
    
       Dim minimalPotency As Double, minimalRemainder As Double, potency As Double
    
       radicand = Int(radicand)
    
       degree = Abs(degree)
    
       fullRadicand = CStr(radicand)
    
       missingZeroes = degree - Len(fullRadicand) Mod degree
    
       If missingZeroes < degree Then
    
          fullRadicand = String(missingZeroes, "0") + fullRadicand
    
       End If
    
       remainder = 0
    
       RootShift = 0
    
       Do While fullRadicand <> ""
    
          partialRadicand = Left(fullRadicand, degree)
    
          fullRadicand = Mid(fullRadicand, degree + 1)
    
          minimalPotency = (RootShift * 10) ^ degree
    
          minimalRemainder = remainder * 10 ^ degree + Val(partialRadicand)
    
          For digit = 9 To 0 Step -1
    
              potency = (RootShift * 10 + digit) ^ degree - minimalPotency
    
              If potency <= minimalRemainder Then
    
                 Exit For
    
              End If
    
          Next
    
          RootShift = RootShift * 10 + digit
    
          remainder = minimalRemainder - potency
    
       Loop
    
    End Function
    

提交回复
热议问题