Im using the BigInteger class in System.Numerics, and my problem is that there is no build in function for Sqrt in the class. So I would have to design my own, and I used this:Private Function SqrtN(ByVal N As BigInteger) As BigInteger
If (0 = N) Then Return 0
Dim n1 As BigInteger = (N >> 1) + 1
Dim n2 As BigInteger = (n1 + (N / n1)) >> 1
While (n2 < n1)
n1 = n2
n2 = (n1 + (N / n1)) >> 1
End While
Return n1
End Function
Which is the Newton–Raphson[^] method. The question is, does anyone now of a faster or better way for finding square root of integers?
解决方案All the best methods for sqrt() that I can remember from working on math runtime libraries (as the dinosaurs called them!) involved an initial rational function approximation (the quotient of a couple of cubics or thereabouts) followed by one (or maybe two) N-R iteration to clean up. Each iteration approximately doubles the number of significant bits in the answer (quadratic convergence), so in the 56-bit-mantissa-on-16-bit-hardware world we lived in then it all worked well. Multiple precision division was the very expensive operation, and a few more multiplications to save a division paid off. In your case, I suspect that initial approximation won''t help much, because you''re going to be doing so many N-R iterations. Depends on the size of your numbers, of course. If you''re playing with, say, less than 128 bits, then the rational function might be worth a bit, but if you''re playing with really big numbers, nothing much will help.
Have fun, and thanks for the opportunity to reminisce!
Peter