include/functions/math.hpp
BigInt sqrt(const BigInt& num) {
    if (num < 0)
        throw std::invalid_argument("Cannot compute square root of a negative integer");

    // Optimisations for small inputs:
    if (num == 0)
        return 0;
    else if (num < 4)
        return 1;
    else if (num < 9)
        return 2;
    else if (num < 16)
        return 3;

    BigInt sqrt_prev = -1;
    // The value for `sqrt_current` is chosen close to that of the actual
    // square root.
    // Since a number's square root has at least one less than half as many
    // digits as the number,
    //     sqrt_current = 10^(half_the_digits_in_num - 1)
    BigInt sqrt_current = big_pow10(num.to_string().size() / 2 - 1);

    while (abs(sqrt_current - sqrt_prev) > 1) {
        sqrt_prev = sqrt_current;
        sqrt_current = (num / sqrt_prev + sqrt_prev) / 2;
    }

    return sqrt_current;
}
/*
    sqrt
    ----
    Returns the positive integer square root of a BigInt using Newton's method.
    NOTE: the input must be non-negative.
*/
sqrt
Returns the positive integer square root of a BigInt using Newton's method.
NOTE: the input must be non-negative.
sqrt Returns the positive integer square root of a BigInt using Newton ' s method . NOTE : the input must be non - negative .
BigInt sqrt(const BigInt& num) {
    if (num < 0)
        throw std::invalid_argument("Cannot compute square root of a negative integer");
    if (num == 0)
        return 0;
    else if (num < 4)
        return 1;
    else if (num < 9)
        return 2;
    else if (num < 16)
        return 3;
    BigInt sqrt_prev = -1;
    BigInt sqrt_current = big_pow10(num.to_string().size() / 2 - 1);
    while (abs(sqrt_current - sqrt_prev) > 1) {
        sqrt_prev = sqrt_current;
        sqrt_current = (num / sqrt_prev + sqrt_prev) / 2;
    }
    return sqrt_current;
}
BigInt sqrt ( const BigInt & num ) { if ( num < 0 ) throw std :: invalid_argument ( " " ) ; if ( num == 0 ) return 0 ; else if ( num < 4 ) return 1 ; else if ( num < 9 ) return 2 ; else if ( num < 16 ) return 3 ; BigInt sqrt_prev = -1 ; BigInt sqrt_current = big_pow10 ( num . to_string ( ) . size ( ) / 2 - 1 ) ; while ( abs ( sqrt_current - sqrt_prev ) > 1 ) { sqrt_prev = sqrt_current ; sqrt_current = ( num / sqrt_prev + sqrt_prev ) / 2 ; } return sqrt_current ; }
sqrt
Returns the positive integer square root of a BigInt using Newton's method.
sqrt Returns the positive integer square root of a BigInt using Newton ' s method .
// Optimisations for small inputs: // The value for `sqrt_current` is chosen close to that of the actual // square root. // Since a number's square root has at least one less than half as many // digits as the number, //     sqrt_current = 10^(half_the_digits_in_num - 1)