我如何在c ++中获得sqrt到biginteger数 [英] how i get sqrt to biginteger number in c++

查看:78
本文介绍了我如何在c ++中获得sqrt到biginteger数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在c ++中获得sqrt()到biginteger数字

how i get sqrt() to biginteger number in c++

推荐答案

我不完全了解这个主题,但是因为你正在处理一种整数,您可能需要自己编写方法。根函数通常提供浮点结果(即使对于整数输入),我也不知道通用的大型浮点类型(或库)。
I don''t know the subject thoroughly but since you are dealing with a type of integer, you probably will need to write the method yourself. Root functions generally provide floating point results (even for integer input), and I am not aware of a generalized large float type (or library).


您可以使用GMP库 [ ^ ]。


这里我将算法从Solution 2移植到BigInteger。



Here my stab at porting the algorithm from Solution 2 to BigInteger.

using namespace System;
using namespace System::Numerics;
...
        static BigInteger SQRT(BigInteger y)
        {
            if (y <= BigInteger::Zero)
            {
                if (y != BigInteger::Zero)
                {
                    return BigInteger::Negate(BigInteger::One);
                }
                return BigInteger::Zero;
            }

            /* select a good starting value using binary logarithms: */
            BigInteger x_old(4);
            BigInteger testy(16);   // testy = x_old ^ 2

            while(true)
            {
                if ( y <= testy)
                {
                    break;
                }
                testy <<= 2L;
                x_old <<= 1L;
            }
            /* x_old >= sqrt(y) */
            /* use the Babylonian method to arrive at the integer square root: */
            BigInteger x_new;
            while(true)
            {
                x_new = (BigInteger::Add( (y / x_old), x_old ) ) / 2L;
                if (x_old <= x_new)
                {
                    break;
                }
                x_old = x_new;
            }
            return x_old;
        }



希望有所帮助。


Hope that helps.


这篇关于我如何在c ++中获得sqrt到biginteger数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆