biginteger 原理_BigInteger的平方根算法

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值