数学数据结构

· · 算法·理论

高精度

//@formatter:off
class BigInt{private:vector<signed>digits;bool is_negative;static const size_t KARATSUBA_THRESHOLD=32;void remove_leading_zeros(){while(digits.size()>1&&digits.back()==0)digits.pop_back();if(is_zero())is_negative=false;}void normalize(){remove_leading_zeros();}signed compare_abs(const BigInt&other)const{if(digits.size()!=other.digits.size())return digits.size()<other.digits.size()?-1:1;for(signed i=digits.size()-1;i>=0;i--)if(digits[i]!=other.digits[i])return digits[i]<other.digits[i]?-1:1;return 0;}BigInt shift_left(size_t m)const{if(is_zero())return BigInt(0);BigInt res=*this;res.digits.insert(res.digits.begin(),m,0);res.normalize();return res;}BigInt get_high(size_t k)const{BigInt res;res.is_negative=false,res.digits.clear();if(k>=digits.size()){res.digits.push_back(0);return res;}for(size_t i=k;i<digits.size();++i)res.digits.push_back(digits[i]);res.normalize();return res;}BigInt get_low(size_t k)const{BigInt res;res.is_negative=false,res.digits.clear();size_t len=min(k,digits.size());for(size_t i=0;i<len;++i)res.digits.push_back(digits[i]);res.normalize();return res;}public:BigInt():is_negative(false){digits.push_back(0);}BigInt(long long num){if(num<0)is_negative=true,num=-num;else is_negative=false;if(num==0)digits.push_back(0);else while(num>0)digits.push_back(num%10),num/=10;}BigInt(const string&str){if(str.empty()){digits.push_back(0),is_negative=false;return;}size_t start=0;if(str[0]=='-')is_negative=true,start=1;else if(str[0]=='+')is_negative=false,start=1;else is_negative=false;while(start<str.size()&&str[start]=='0')start++;if(start==str.size()){digits.push_back(0),is_negative=false;return;}digits.reserve(str.size()-start);for(signed i=str.size()-1;i>=static_cast<signed>(start);i--){if(!isdigit(str[i]))throw invalid_argument("Invalid character in number string");digits.push_back(str[i]-'0');}remove_leading_zeros();}BigInt(const BigInt&other)=default;BigInt&operator=(const BigInt&other)=default;bool is_zero()const{return digits.size()==1&&digits[0]==0;}BigInt abs()const{BigInt result=*this;result.is_negative=false;return result;}bool operator==(const BigInt&other)const{if(is_zero()&&other.is_zero())return true;if(is_negative!=other.is_negative)return false;return compare_abs(other)==0;}bool operator!=(const BigInt&other)const{return!(*this==other);}bool operator<(const BigInt&other)const{if(is_negative!=other.is_negative)return is_negative;signed cmp=compare_abs(other);return is_negative?(cmp>0):(cmp<0);}bool operator<=(const BigInt&other)const{return*this<other||*this==other;}bool operator>(const BigInt&other)const{return!(*this<=other);}bool operator>=(const BigInt&other)const{return!(*this<other);}BigInt operator-()const{BigInt result=*this;if(!result.is_zero())result.is_negative=!result.is_negative;return result;}BigInt operator+(const BigInt&other)const{if(is_negative!=other.is_negative)return is_negative?(other-(-*this)):(*this-(-other));BigInt result;result.is_negative=is_negative,result.digits.clear();const size_t max_size=max(digits.size(),other.digits.size());result.digits.reserve(max_size+1);signed carry=0;for(size_t i=0;i<max_size||carry;i++){signed sum=carry;if(i<digits.size())sum+=digits[i];if(i<other.digits.size())sum+=other.digits[i];result.digits.push_back(sum%10),carry=sum/10;}result.normalize();return result;}BigInt operator-(const BigInt&other)const{if(is_negative!=other.is_negative)return*this+(-other);if(compare_abs(other)<0){BigInt result=other-*this;result.is_negative=!is_negative;return result;}BigInt result;result.is_negative=is_negative,result.digits.clear(),result.digits.reserve(digits.size());signed borrow=0;for(size_t i=0;i<digits.size();i++){signed diff=digits[i]-borrow;if(i<other.digits.size())diff-=other.digits[i];if(diff<0)diff+=10,borrow=1;else borrow=0;result.digits.push_back(diff);}result.normalize();return result;}BigInt operator*(const BigInt&other)const{if(is_zero()||other.is_zero())return BigInt(0);if(digits.size()<KARATSUBA_THRESHOLD||other.digits.size()<KARATSUBA_THRESHOLD){BigInt result;result.is_negative=(is_negative!=other.is_negative),result.digits.resize(digits.size()+other.digits.size(),0);for(size_t i=0;i<digits.size();i++){signed carry=0;for(size_t j=0;j<other.digits.size()||carry;j++){long long product=result.digits[i+j]+static_cast<long long>(digits[i])*(j<other.digits.size()?other.digits[j]:0)+carry;result.digits[i+j]=product%10;carry=product/10;}}result.normalize();return result;}size_t n=max(digits.size(),other.digits.size());size_t m=(n+1)/2;BigInt a0=get_low(m);BigInt a1=get_high(m);BigInt b0=other.get_low(m);BigInt b1=other.get_high(m);BigInt z0=a0*b0;BigInt z1=(a0+a1)*(b0+b1);BigInt z2=a1*b1;BigInt result=z2.shift_left(2*m)+(z1-z2-z0).shift_left(m)+z0;result.is_negative=(is_negative!=other.is_negative),result.normalize();return result;}BigInt operator/(const BigInt&other)const{if(other.is_zero())throw invalid_argument("Division by zero");if(is_zero())return BigInt(0);BigInt dividend=abs();BigInt divisor=other.abs();if(dividend<divisor)return BigInt(0);BigInt quotient;quotient.is_negative=(is_negative!=other.is_negative),quotient.digits.clear();BigInt current;for(signed i=dividend.digits.size()-1;i>=0;i--){current.digits.insert(current.digits.begin(),dividend.digits[i]),current.normalize();if(current<divisor){quotient.digits.insert(quotient.digits.begin(),0);continue;}signed left=0,right=9,digit=0;while(left<=right){signed mid=(left+right)/2;BigInt temp_product=divisor*BigInt(mid);if(temp_product<=current)digit=mid,left=mid+1;else right=mid-1;}quotient.digits.insert(quotient.digits.begin(),digit);current=current-(divisor*BigInt(digit));}quotient.normalize();return quotient;}BigInt operator%(const BigInt&other)const{if(other.is_zero())throw invalid_argument("Modulo by zero");BigInt quotient=*this/other;BigInt remainder=*this-quotient*other;return remainder;}friend ostream&operator<<(ostream&os,const BigInt&num){if(num.is_negative)os<<'-';for(signed i=num.digits.size()-1;i>=0;i--)os<<num.digits[i];return os;}friend istream&operator>>(istream&is,BigInt&num){string str;is>>str,num=BigInt(str);return is;}};
//@formatter:on

分数

//@formatter:off
class Fraction{private:using FractionInt=__int128;FractionInt num,den;void reduce(){if(den==0)throw std::runtime_error("Denominator cannot be zero");if(num==0){den=1;return;}if(den<0){num=-num;den=-den;}FractionInt g=__gcd(num,den);num/=g;den/=g;}public:Fraction():num(0),den(1){}Fraction(const FractionInt&n):num(n),den(1){reduce();}Fraction(const FractionInt&n,const FractionInt&d):num(n),den(d){reduce();}Fraction(const Fraction&)=default;Fraction&operator=(const Fraction&)=default;Fraction operator+(const Fraction&o)const{return Fraction(num*o.den+den*o.num,den*o.den);}Fraction operator-(const Fraction&o)const{return Fraction(num*o.den-den*o.num,den*o.den);}Fraction operator*(const Fraction&o)const{return Fraction(num*o.num,den*o.den);}Fraction operator/(const Fraction&o)const{return Fraction(num*o.den,den*o.num);}bool operator==(const Fraction&o)const{return num*o.den==den*o.num;}bool operator!=(const Fraction&o)const{return!(*this==o);}bool operator<(const Fraction&o)const{return num*o.den<den*o.num;}bool operator<=(const Fraction&o)const{return!(o<*this);}bool operator>(const Fraction&o)const{return o<*this;}bool operator>=(const Fraction&o)const{return!(*this<o);}struct Improper{FractionInt numerator,denominator;};Improper asImproper()const{return{num,den};}struct Mixed{FractionInt integer,numerator,denominator;};Mixed asMixed()const{FractionInt intPart=num/den,rem=num%den;if(rem<0)rem=-rem;return{intPart,rem,den};}};
//@formatter:on

矩阵

const int mod=1e9+7;
class Matrix {
public: 
    int n=0,m=0;
    vector<vector<int>> mat;
    Matrix(int tp_n,int tp_m):n(tp_n),m(tp_m){
        mat.resize(n,vector<int>(m,0));
    }
    void setIdentity(){
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                mat[i][j]=(i==j?1:0);
            }
        }
    }
    Matrix& operator= (const Matrix& other){
        if (this!=&other) {
            n=other.n;
            m=other.m;
            mat=other.mat;
        }
        return *this;
    }
    Matrix operator* (const Matrix& other) const {
        if(m!=other.n) return Matrix(0,0);
        Matrix ans{n,other.m};
        for(int i=0;i<n;i++){
            for(int j=0;j<other.m;j++){
                int num=0;
                for(int k=0;k<m;k++){
                    (num+=mat[i][k]*other.mat[k][j])%=mod;
                }
                ans.mat[i][j]=num;
            }
        }
        return ans;
    }
    friend istream& operator>>(istream& is, Matrix& cur) {
        for(int i=0;i<cur.n;i++){
            for(int j=0;j<cur.m;j++){
                is>>cur.mat[i][j];
                cur.mat[i][j]%=mod;
            }
        }
        return is;
    };
    friend ostream& operator<<(ostream& os, const Matrix& cur) {
        for(int i=0;i<cur.n;i++){
            for(int j=0;j<cur.m;j++){
                if(j) os<<" ";
                os<<cur.mat[i][j];
            }
            os<<endl;
        }
        return os;
    };
};
inline int sum(Matrix x){
    int ans=0;
    for(int i=0;i<x.n;i++){
        for(int j=0;j<x.m;j++){
            (ans+=x.mat[i][j])%=mod;
        }
    }
    return ans;
}
inline Matrix qpow(Matrix base,int b){
    Matrix ans{base.n,base.m};
    ans.setIdentity();
    while(b){
        if(b&1){
            ans=ans*base;
        }
        base=base*base;
        b>>=1;
    }
    return ans;
}

线性基

template <int N>
class Basis {
    using T = conditional_t < N < 32, unsigned int, unsigned long long>;

    array < T, N + 1 > d;
    bool easy = false;
    vector<T> base;

public:
    Basis(): d{}, easy(false) {}

    inline void insert(T val) {
        easy = false;
        for (int i = N; i >= 0; i--) {
            if (val & ((T)1 << i)) {
                if (!d[i]) {
                    d[i] = val;
                    return;
                } else val ^= d[i];
            }
        }
    }

    inline void reduce() {
        for (int i = N; i >= 0; i--) {
            if (!d[i]) continue;
            for (int j = i - 1; j >= 0; j--) {
                if (d[i] & ((T)1 << j)) {
                    d[i] ^= d[j];
                }
            }
        }
        base.clear();
        for (int i = 0; i <= N; i++) {
            if (d[i]) base.push_back(d[i]);
        }
        easy = true;
    }

    inline T query_max() {
        T res = 0;
        for (int i = N; i >= 0; i--) {
            if ((res ^ d[i]) > res) res ^= d[i];
        }
        return res;
    }

    inline T query_min() {
        for (int i = 0; i <= N; i++) {
            if (d[i]) return d[i];
        }
        return 0;
    }

    inline T query_rank(T k) {
        if (!k) return 0;
        if (!easy) reduce();
        if (k > ((T)1 << base.size())) return -1;
        T res = 0;
        k--;
        for (size_t i = 0; i < base.size(); i++) {
            if (k & ((T)1 << i)) res ^= base[i];
        }
        return res;
    }
};
Basis<60> basis;

进制数

//@formatter:off
class CustomBaseNumber{public:static const int DEFAULT_DIGITS=32;static const int MAX_DIGITS=64;CustomBaseNumber(int base,uint64_t value=0,int digits=DEFAULT_DIGITS):m_base(base),m_digits(digits),m_value(0){if(base<2||base>36)throw std::invalid_argument("base must be in [2, 36]");if(digits<1||digits>MAX_DIGITS)throw std::invalid_argument("digits must be between 1 and 64");m_pows[0]=1;m_maxValue=1;for(int i=0;i<digits;++i){if(m_maxValue>UINT64_MAX/base)throw std::overflow_error("base^digits exceeds 64-bit limit");m_maxValue*=base;if(i+1<digits)m_pows[i+1]=m_maxValue;}m_value=value%m_maxValue;}static CustomBaseNumber fromUllong(uint64_t value,int base,int digits=DEFAULT_DIGITS){return CustomBaseNumber(base,value,digits);}static CustomBaseNumber fromString(const std::string&str,int base,int digits=DEFAULT_DIGITS){CustomBaseNumber num(base,0,digits);uint64_t value=0;for(char ch:str){int digit;if(ch>='0'&&ch<='9')digit=ch-'0';else if(ch>='A'&&ch<='Z')digit=ch-'A'+10;else if(ch>='a'&&ch<='z')digit=ch-'a'+10;else throw std::invalid_argument("invalid character");if(digit>=base)throw std::invalid_argument("digit out of range");if(value>(UINT64_MAX-digit)/base)throw std::overflow_error("number too large");value=value*base+digit;}num.m_value=value%num.m_maxValue;return num;}int getDigit(int pos)const{if(pos<0||pos>=m_digits)throw std::out_of_range("digit position out of range");return(int)((m_value/m_pows[pos])%m_base);}void setDigit(int pos,int value){if(pos<0||pos>=m_digits)throw std::out_of_range("digit position out of range");if(value<0||value>=m_base)throw std::invalid_argument("digit value out of range");uint64_t cur=(m_value/m_pows[pos])%m_base;m_value+=(uint64_t)(value-cur)*m_pows[pos];}void flipDigit(int pos){int cur=getDigit(pos);setDigit(pos,m_base-1-cur);}CustomBaseNumber shiftLeft(int n=1)const{if(n<0)throw std::invalid_argument("shift count must be non-negative");if(n==0)return*this;if(n>=m_digits)return CustomBaseNumber(m_base,0,m_digits);uint64_t val=(m_value*m_pows[n])%m_maxValue;return fromUllong(val,m_base,m_digits);}CustomBaseNumber shiftRight(int n=1)const{if(n<0)throw std::invalid_argument("shift count must be non-negative");if(n==0)return*this;if(n>=m_digits)return CustomBaseNumber(m_base,0,m_digits);uint64_t val=m_value/m_pows[n];return fromUllong(val,m_base,m_digits);}CustomBaseNumber operator<<(int shift)const{return shiftLeft(shift);}CustomBaseNumber operator>>(int shift)const{return shiftRight(shift);}CustomBaseNumber&operator<<=(int shift){*this=shiftLeft(shift);return*this;}CustomBaseNumber&operator>>=(int shift){*this=shiftRight(shift);return*this;}CustomBaseNumber operator-()const{if(m_value==0)return*this;return fromUllong(m_maxValue-m_value,m_base,m_digits);}CustomBaseNumber operator+()const{return*this;}CustomBaseNumber operator+(const CustomBaseNumber&other)const{check_compatible(other);__int128 temp=(__int128)m_value+other.m_value;uint64_t val=(uint64_t)(temp%m_maxValue);return fromUllong(val,m_base,m_digits);}CustomBaseNumber operator-(const CustomBaseNumber&other)const{check_compatible(other);__int128 temp=(__int128)m_value-other.m_value;temp%=m_maxValue;if(temp<0)temp+=m_maxValue;return fromUllong((uint64_t)temp,m_base,m_digits);}CustomBaseNumber operator*(const CustomBaseNumber&other)const{check_compatible(other);__int128 temp=(__int128)m_value*other.m_value;uint64_t val=(uint64_t)(temp%m_maxValue);return fromUllong(val,m_base,m_digits);}CustomBaseNumber operator/(const CustomBaseNumber&other)const{check_compatible(other);if(other.m_value==0)throw std::runtime_error("division by zero");uint64_t val=m_value/other.m_value;return fromUllong(val,m_base,m_digits);}CustomBaseNumber operator%(const CustomBaseNumber&other)const{check_compatible(other);if(other.m_value==0)throw std::runtime_error("modulo by zero");uint64_t val=m_value%other.m_value;return fromUllong(val,m_base,m_digits);}CustomBaseNumber&operator+=(const CustomBaseNumber&other){*this=*this+other;return*this;}CustomBaseNumber&operator-=(const CustomBaseNumber&other){*this=*this-other;return*this;}CustomBaseNumber&operator*=(const CustomBaseNumber&other){*this=*this*other;return*this;}CustomBaseNumber&operator/=(const CustomBaseNumber&other){*this=*this/other;return*this;}CustomBaseNumber&operator%=(const CustomBaseNumber&other){*this=*this%other;return*this;}CustomBaseNumber&operator++(){if(++m_value==m_maxValue)m_value=0;return*this;}CustomBaseNumber operator++(int){CustomBaseNumber temp=*this;++(*this);return temp;}CustomBaseNumber&operator--(){if(m_value==0)m_value=m_maxValue-1;else--m_value;return*this;}CustomBaseNumber operator--(int){CustomBaseNumber temp=*this;--(*this);return temp;}bool operator==(const CustomBaseNumber&other)const{return m_base==other.m_base&&m_digits==other.m_digits&&m_value==other.m_value;}bool operator!=(const CustomBaseNumber&other)const{return!(*this==other);}bool operator<(const CustomBaseNumber&other)const{check_compatible(other);return m_value<other.m_value;}bool operator>(const CustomBaseNumber&other)const{return other<*this;}bool operator<=(const CustomBaseNumber&other)const{return!(*this>other);}bool operator>=(const CustomBaseNumber&other)const{return!(*this<other);}operator size_t()const{return(size_t)m_value;}explicit operator bool()const{return m_value!=0;}friend std::ostream&operator<<(std::ostream&os,const CustomBaseNumber&num){os<<num.toString();return os;}friend std::istream&operator>>(std::istream&is,CustomBaseNumber&num){std::string str;is>>str;num=fromString(str,num.m_base,num.m_digits);return is;}std::string toString()const{if(m_value==0)return"0";uint64_t val=m_value;std::string result;while(val>0){int digit=val%m_base;char ch=(digit<10)?('0'+digit):('A'+(digit-10));result.push_back(ch);val/=m_base;}std::reverse(result.begin(),result.end());return result;}std::string toFixedString()const{std::string s=toString();while(s.length()<(size_t)m_digits)s="0"+s;return s;}uint64_t toUllong()const{return m_value;}uint64_t getMaxValue()const{return m_maxValue;}int getBase()const{return m_base;}int getDigits()const{return m_digits;}private:int m_base;int m_digits;uint64_t m_value;uint64_t m_maxValue;uint64_t m_pows[64];void check_compatible(const CustomBaseNumber&other)const{if(m_base!=other.m_base||m_digits!=other.m_digits)throw std::invalid_argument("operands must have same base and digits");}};
//@formatter:on

展开形式

高精度

class BigInt {
private:
    vector<int> digits;  // 倒序存储数字,每位0-9
    bool is_negative;    // 符号标志
    static const size_t KARATSUBA_THRESHOLD = 32;  // Karatsuba算法阈值(小数字用竖式乘法)
    // 内部工具函数
    void remove_leading_zeros() {
        while (digits.size() > 1 && digits.back() == 0) digits.pop_back();
        if (is_zero()) is_negative = false;
    };
    void normalize() {
        remove_leading_zeros();
    };
    int compare_abs(const BigInt& other) const {
        if (digits.size() != other.digits.size()) return digits.size() < other.digits.size() ? -1 : 1;
        for (int i = digits.size() - 1; i >= 0; i--) if (digits[i] != other.digits[i]) return digits[i] < other.digits[i] ? -1 : 1;
        return 0;
    };
    BigInt shift_left(size_t m) const { // 左移m位(乘以10^m)
        if (is_zero()) return BigInt(0);
        BigInt res = *this;
        res.digits.insert(res.digits.begin(), m, 0);  // 倒序存储,末尾加0即高位扩展
        res.normalize();
        return res;
    };
    BigInt get_high(size_t k) const { // 获取高位k位
        BigInt res;
        res.is_negative = false, res.digits.clear();
        if (k >= digits.size()) {
            res.digits.push_back(0);
            return res;
        }
        for (size_t i = k; i < digits.size(); ++i) res.digits.push_back(digits[i]); // 从第k位开始取到末尾(高位部分)
        res.normalize();
        return res;
    };
    BigInt get_low(size_t k) const { // 获取低位k位
        BigInt res;
        res.is_negative = false, res.digits.clear();
        size_t len = min(k, digits.size());
        for (size_t i = 0; i < len; ++i) res.digits.push_back(digits[i]); // 取前k位(低位部分)
        res.normalize();
        return res;
    };
public:
    // 构造函数
    BigInt() : is_negative(false) {
        digits.push_back(0);
    }
    BigInt(long long num) {
        if (num < 0) is_negative = true, num = -num;
        else is_negative = false;
        if (num == 0) digits.push_back(0);
        else while (num > 0) digits.push_back(num % 10), num /= 10;
    }
    BigInt(const string& str) {
        if (str.empty()) {
            digits.push_back(0), is_negative = false;
            return;
        }
        size_t start = 0;
        if (str[0] == '-') is_negative = true, start = 1;
        else if (str[0] == '+') is_negative = false, start = 1;
        else is_negative = false;
        while (start < str.size() && str[start] == '0') start++; // 跳过前导零
        if (start == str.size()) {
            digits.push_back(0), is_negative = false;
            return;
        }
        // 预分配空间提高效率
        digits.reserve(str.size() - start);
        for (int i = str.size() - 1; i >= static_cast<int>(start); i--) {
            if (!isdigit(str[i])) throw invalid_argument("Invalid character in number string");
            digits.push_back(str[i] - '0');
        }
        remove_leading_zeros();
    };
    BigInt(const BigInt& other) = default;
    BigInt& operator=(const BigInt& other) = default;
    // 基本信息
    bool is_zero() const {
        return digits.size() == 1 && digits[0] == 0;
    }
    BigInt abs() const {
        BigInt result = *this;
        result.is_negative = false;
        return result;
    };
    // 比较运算符
    bool operator==(const BigInt& other) const {
        if (is_zero() && other.is_zero()) return true;
        if (is_negative != other.is_negative) return false;
        return compare_abs(other) == 0;
    };
    bool operator!=(const BigInt& other) const {
        return !(*this == other);
    }
    bool operator<(const BigInt& other) const {
        if (is_negative != other.is_negative) return is_negative;
        int cmp = compare_abs(other);
        return is_negative ? (cmp > 0) : (cmp < 0);
    };
    bool operator<=(const BigInt& other) const {
        return *this < other || *this == other;
    }
    bool operator>(const BigInt& other) const {
        return !(*this <= other);
    }
    bool operator>=(const BigInt& other) const {
        return !(*this < other);
    }
    // 算术运算符
    BigInt operator-() const {
        BigInt result = *this;
        if (!result.is_zero()) result.is_negative = !result.is_negative;
        return result;
    };
    BigInt operator+(const BigInt& other) const {
        if (is_negative != other.is_negative) return is_negative ? (other - (-*this)) : (*this - (-other));// 处理符号不同的情况:转换为减法
        BigInt result;
        result.is_negative = is_negative, result.digits.clear();
        const size_t max_size = max(digits.size(), other.digits.size());
        result.digits.reserve(max_size + 1);
        int carry = 0;
        for (size_t i = 0; i < max_size || carry; i++) {
            int sum = carry;
            if (i < digits.size()) sum += digits[i];
            if (i < other.digits.size()) sum += other.digits[i];
            result.digits.push_back(sum % 10), carry = sum / 10;
        }
        result.normalize();
        return result;
    };
    BigInt operator-(const BigInt& other) const {
        if (is_negative != other.is_negative) return *this + (-other); // 处理符号不同的情况:转换为加法
        if (compare_abs(other) < 0) { // 同号相减,确保被减数的绝对值大于减数
            BigInt result = other - *this;
            result.is_negative = !is_negative;
            return result;
        }
        BigInt result;
        result.is_negative = is_negative, result.digits.clear(), result.digits.reserve(digits.size());
        int borrow = 0;
        for (size_t i = 0; i < digits.size(); i++) {
            int diff = digits[i] - borrow;
            if (i < other.digits.size()) diff -= other.digits[i];
            if (diff < 0) diff += 10, borrow = 1;
            else borrow = 0;
            result.digits.push_back(diff);
        }
        result.normalize();
        return result;
    };
    BigInt operator*(const BigInt& other) const {
        // 优化:Karatsuba乘法(O(n^log3)≈O(n^1.58))
        if (is_zero() || other.is_zero()) return BigInt(0);
        // 小数字用原竖式乘法(避免递归开销)
        if (digits.size() < KARATSUBA_THRESHOLD || other.digits.size() < KARATSUBA_THRESHOLD) {
            BigInt result;
            result.is_negative = (is_negative != other.is_negative), result.digits.resize(digits.size() + other.digits.size(), 0);
            for (size_t i = 0; i < digits.size(); i++) {
                int carry = 0;
                for (size_t j = 0; j < other.digits.size() || carry; j++) {
                    long long product = result.digits[i + j] + static_cast<long long>(digits[i]) * (j < other.digits.size() ? other.digits[j] : 0) + carry;
                    result.digits[i + j] = product % 10;
                    carry = product / 10;
                }
            }
            result.normalize();
            return result;
        }
        // Karatsuba核心逻辑:a = a1*10^m + a0, b = b1*10^m + b0
        size_t n = max(digits.size(), other.digits.size());
        size_t m = (n + 1) / 2;  // 分割点(高位m位,低位n-m位)
        BigInt a0 = get_low(m);    // a的低位
        BigInt a1 = get_high(m);   // a的高位
        BigInt b0 = other.get_low(m);  // b的低位
        BigInt b1 = other.get_high(m); // b的高位
        // 3次乘法替代4次:z0=a0*b0, z1=(a0+a1)(b0+b1), z2=a1*b1
        BigInt z0 = a0 * b0;
        BigInt z1 = (a0 + a1) * (b0 + b1);
        BigInt z2 = a1 * b1;
        // 结果 = z2*10^(2m) + (z1-z2-z0)*10^m + z0
        BigInt result = z2.shift_left(2 * m) + (z1 - z2 - z0).shift_left(m) + z0;
        result.is_negative = (is_negative != other.is_negative), result.normalize();
        return result;
    };
    BigInt operator/(const BigInt& other) const {
        if (other.is_zero()) throw invalid_argument("Division by zero");
        if (is_zero()) return BigInt(0);
        BigInt dividend = abs();
        BigInt divisor = other.abs();
        if (dividend < divisor) return BigInt(0);
        BigInt quotient;
        quotient.is_negative = (is_negative != other.is_negative), quotient.digits.clear();
        BigInt current;
        for (int i = dividend.digits.size() - 1; i >= 0; i--) {
            current.digits.insert(current.digits.begin(), dividend.digits[i]), current.normalize();
            if (current < divisor) {
                quotient.digits.insert(quotient.digits.begin(), 0);
                continue;
            }
            int left = 0, right = 9, digit = 0;
            while (left <= right) {
                int mid = (left + right) / 2;
                BigInt temp_product = divisor * BigInt(mid);
                if (temp_product <= current) digit = mid, left = mid + 1;
                else right = mid - 1;
            }
            quotient.digits.insert(quotient.digits.begin(), digit);
            current = current - (divisor * BigInt(digit));
        }
        quotient.normalize();
        return quotient;
    };
    BigInt operator%(const BigInt& other) const {
        if (other.is_zero()) throw invalid_argument("Modulo by zero");
        BigInt quotient = *this / other;
        BigInt remainder = *this - quotient * other;
        return remainder;
    };
    // 输入输出
    friend ostream& operator<<(ostream& os, const BigInt& num) {
        if (num.is_negative) os << '-';
        for (int i = num.digits.size() - 1; i >= 0; i--) os << num.digits[i];
        return os;
    };
    friend istream& operator>>(istream& is, BigInt& num) {
        string str;
        is >> str, num = BigInt(str);
        return is;
    };
};

分数

class Fraction {
private:
    using FractionInt = __int128;   // 可替换为 BigInt

    FractionInt num;   // 分子
    FractionInt den;   // 分母(正)

    void reduce() {
        if (den == 0) throw std::runtime_error("Denominator cannot be zero");
        if (num == 0) {
            den = 1;
            return;
        }
        if (den < 0) {
            num = -num;
            den = -den;
        }
        FractionInt g = __gcd(num, den);
        num /= g;
        den /= g;
    }

public:
    Fraction() : num(0), den(1) {}
    Fraction(const FractionInt& n) : num(n), den(1) { reduce(); }
    Fraction(const FractionInt& n, const FractionInt& d) : num(n), den(d) { reduce(); }
    Fraction(const Fraction&) = default;
    Fraction& operator=(const Fraction&) = default;

    // 算术运算
    Fraction operator+(const Fraction& other) const {
        return Fraction(num * other.den + den * other.num, den * other.den);
    }
    Fraction operator-(const Fraction& other) const {
        return Fraction(num * other.den - den * other.num, den * other.den);
    }
    Fraction operator*(const Fraction& other) const {
        return Fraction(num * other.num, den * other.den);
    }
    Fraction operator/(const Fraction& other) const {
        return Fraction(num * other.den, den * other.num);
    }

    // 比较运算
    bool operator==(const Fraction& other) const {
        return num * other.den == den * other.num;
    }
    bool operator!=(const Fraction& other) const { return !(*this == other); }
    bool operator<(const Fraction& other) const {
        return num * other.den < den * other.num;
    }
    bool operator<=(const Fraction& other) const { return !(other < *this); }
    bool operator>(const Fraction& other) const { return other < *this; }
    bool operator>=(const Fraction& other) const { return !(*this < other); }

    // 假分数形式(分子分母)
    struct Improper {
        FractionInt numerator;
        FractionInt denominator;
    };
    Improper asImproper() const { return {num, den}; }

    // 带分数形式(整数部分,真分数分子,分母)
    struct Mixed {
        FractionInt integer;
        FractionInt numerator;
        FractionInt denominator;
    };
    Mixed asMixed() const {
        FractionInt intPart = num / den;
        FractionInt rem = num % den;
        if (rem < 0) rem = -rem;
        return {intPart, rem, den};
    }
};

进制数

class CustomBaseNumber {
public:
    // 默认位数(32位)和最大位数(64位)
    static const int DEFAULT_DIGITS = 32;
    static const int MAX_DIGITS = 64;

    // ---------- 构造函数 ----------
    // 参数:基数 base(2~36),初始数值 value(默认为0),位数 digits(默认为32)
    CustomBaseNumber(int base, uint64_t value = 0, int digits = DEFAULT_DIGITS)
        : m_base(base), m_digits(digits), m_value(0) {
        // 参数合法性检查
        if (base < 2 || base > 36)
            throw std::invalid_argument("base must be in [2, 36]");
        if (digits < 1 || digits > MAX_DIGITS)
            throw std::invalid_argument("digits must be between 1 and 64");

        // 预计算各数位的权值 m_pows[pos] = base^pos,以及最大值 m_maxValue = base^digits
        m_pows[0] = 1;
        m_maxValue = 1;
        for (int i = 0; i < digits; ++i) {
            // 检查溢出:若 m_maxValue * base 超过 uint64_t 上限则报错
            if (m_maxValue > UINT64_MAX / base)
                throw std::overflow_error("base^digits exceeds 64-bit limit");
            m_maxValue *= base;
            if (i + 1 < digits)
                m_pows[i + 1] = m_maxValue;
        }
        // 将数值限制在 [0, m_maxValue-1] 范围内(自动回绕)
        m_value = value % m_maxValue;
    }

    // ---------- 静态工厂方法 ----------
    // 从 uint64_t 构造
    static CustomBaseNumber fromUllong(uint64_t value, int base, int digits = DEFAULT_DIGITS) {
        return CustomBaseNumber(base, value, digits);
    }

    // 从字符串构造(按给定基数解析)
    static CustomBaseNumber fromString(const std::string& str, int base, int digits = DEFAULT_DIGITS) {
        CustomBaseNumber num(base, 0, digits);
        uint64_t value = 0;
        for (char ch : str) {
            int digit;
            if (ch >= '0' && ch <= '9')
                digit = ch - '0';
            else if (ch >= 'A' && ch <= 'Z')
                digit = ch - 'A' + 10;
            else if (ch >= 'a' && ch <= 'z')
                digit = ch - 'a' + 10;
            else
                throw std::invalid_argument("invalid character");
            if (digit >= base)
                throw std::invalid_argument("digit out of range");
            if (value > (UINT64_MAX - digit) / base)
                throw std::overflow_error("number too large");
            value = value * base + digit;
        }
        num.m_value = value % num.m_maxValue;
        return num;
    }

    // ---------- 位/数位访问 ----------
    // 获取第 pos 位的数字(0 为最低位)
    int getDigit(int pos) const {
        if (pos < 0 || pos >= m_digits)
            throw std::out_of_range("digit position out of range");
        return (int)((m_value / m_pows[pos]) % m_base);
    }

    // 设置第 pos 位的数字
    void setDigit(int pos, int value) {
        if (pos < 0 || pos >= m_digits)
            throw std::out_of_range("digit position out of range");
        if (value < 0 || value >= m_base)
            throw std::invalid_argument("digit value out of range");
        uint64_t cur = (m_value / m_pows[pos]) % m_base;
        m_value += (uint64_t)(value - cur) * m_pows[pos];
    }

    // 翻转第 pos 位的数字(变为 (base-1 - 原值))
    void flipDigit(int pos) {
        int cur = getDigit(pos);
        setDigit(pos, m_base - 1 - cur);
    }

    // ---------- 移位操作 ----------
    // 左移 n 位(相当于乘以 base^n),超出位数则回绕或丢弃
    CustomBaseNumber shiftLeft(int n = 1) const {
        if (n < 0)
            throw std::invalid_argument("shift count must be non-negative");
        if (n == 0)
            return *this;
        if (n >= m_digits)
            return CustomBaseNumber(m_base, 0, m_digits);
        uint64_t val = (m_value * m_pows[n]) % m_maxValue;
        return fromUllong(val, m_base, m_digits);
    }

    // 右移 n 位(相当于除以 base^n)
    CustomBaseNumber shiftRight(int n = 1) const {
        if (n < 0)
            throw std::invalid_argument("shift count must be non-negative");
        if (n == 0)
            return *this;
        if (n >= m_digits)
            return CustomBaseNumber(m_base, 0, m_digits);
        uint64_t val = m_value / m_pows[n];
        return fromUllong(val, m_base, m_digits);
    }

    // 运算符重载 << 和 >>
    CustomBaseNumber operator<<(int shift) const { return shiftLeft(shift); }
    CustomBaseNumber operator>>(int shift) const { return shiftRight(shift); }
    CustomBaseNumber& operator<<=(int shift) { *this = shiftLeft(shift); return *this; }
    CustomBaseNumber& operator>>=(int shift) { *this = shiftRight(shift); return *this; }

    // ---------- 一元运算符 ----------
    // 取负(对 m_maxValue 取补码)
    CustomBaseNumber operator-() const {
        if (m_value == 0)
            return *this;
        return fromUllong(m_maxValue - m_value, m_base, m_digits);
    }
    CustomBaseNumber operator+() const { return *this; }

    // ---------- 二元算术运算符(+ - * / %) ----------
    // 注意:所有运算都在模 m_maxValue 下进行,结果自动回绕
    CustomBaseNumber operator+(const CustomBaseNumber& other) const {
        check_compatible(other);
        __int128 temp = (__int128)m_value + other.m_value;
        uint64_t val = (uint64_t)(temp % m_maxValue);
        return fromUllong(val, m_base, m_digits);
    }

    CustomBaseNumber operator-(const CustomBaseNumber& other) const {
        check_compatible(other);
        __int128 temp = (__int128)m_value - other.m_value;
        temp %= m_maxValue;
        if (temp < 0)
            temp += m_maxValue;
        return fromUllong((uint64_t)temp, m_base, m_digits);
    }

    CustomBaseNumber operator*(const CustomBaseNumber& other) const {
        check_compatible(other);
        __int128 temp = (__int128)m_value * other.m_value;
        uint64_t val = (uint64_t)(temp % m_maxValue);
        return fromUllong(val, m_base, m_digits);
    }

    CustomBaseNumber operator/(const CustomBaseNumber& other) const {
        check_compatible(other);
        if (other.m_value == 0)
            throw std::runtime_error("division by zero");
        uint64_t val = m_value / other.m_value;
        return fromUllong(val, m_base, m_digits);
    }

    CustomBaseNumber operator%(const CustomBaseNumber& other) const {
        check_compatible(other);
        if (other.m_value == 0)
            throw std::runtime_error("modulo by zero");
        uint64_t val = m_value % other.m_value;
        return fromUllong(val, m_base, m_digits);
    }

    // 复合赋值运算符
    CustomBaseNumber& operator+=(const CustomBaseNumber& other) { *this = *this + other; return *this; }
    CustomBaseNumber& operator-=(const CustomBaseNumber& other) { *this = *this - other; return *this; }
    CustomBaseNumber& operator*=(const CustomBaseNumber& other) { *this = *this * other; return *this; }
    CustomBaseNumber& operator/=(const CustomBaseNumber& other) { *this = *this / other; return *this; }
    CustomBaseNumber& operator%=(const CustomBaseNumber& other) { *this = *this % other; return *this; }

    // 自增/自减(前缀/后缀),同样是模 m_maxValue 回绕
    CustomBaseNumber& operator++() {
        if (++m_value == m_maxValue)
            m_value = 0;
        return *this;
    }
    CustomBaseNumber operator++(int) {
        CustomBaseNumber temp = *this;
        ++(*this);
        return temp;
    }
    CustomBaseNumber& operator--() {
        if (m_value == 0)
            m_value = m_maxValue - 1;
        else
            --m_value;
        return *this;
    }
    CustomBaseNumber operator--(int) {
        CustomBaseNumber temp = *this;
        --(*this);
        return temp;
    }

    // ---------- 比较运算符 ----------
    bool operator==(const CustomBaseNumber& other) const {
        return m_base == other.m_base && m_digits == other.m_digits && m_value == other.m_value;
    }
    bool operator!=(const CustomBaseNumber& other) const { return !(*this == other); }
    bool operator<(const CustomBaseNumber& other) const {
        check_compatible(other);
        return m_value < other.m_value;
    }
    bool operator>(const CustomBaseNumber& other) const { return other < *this; }
    bool operator<=(const CustomBaseNumber& other) const { return !(*this > other); }
    bool operator>=(const CustomBaseNumber& other) const { return !(*this < other); }

    // ---------- 类型转换 ----------
    operator size_t() const { return (size_t)m_value; }
    explicit operator bool() const { return m_value != 0; }

    // ---------- 流 I/O ----------
    friend std::ostream& operator<<(std::ostream& os, const CustomBaseNumber& num) {
        os << num.toString();
        return os;
    }
    friend std::istream& operator>>(std::istream& is, CustomBaseNumber& num) {
        std::string str;
        is >> str;
        num = fromString(str, num.m_base, num.m_digits);
        return is;
    }

    // ---------- 字符串转换 ----------
    // 返回不带前导零的普通字符串表示
    std::string toString() const {
        if (m_value == 0)
            return "0";
        uint64_t val = m_value;
        std::string result;
        while (val > 0) {
            int digit = val % m_base;
            char ch = (digit < 10) ? ('0' + digit) : ('A' + (digit - 10));
            result.push_back(ch);
            val /= m_base;
        }
        std::reverse(result.begin(), result.end());
        return result;
    }

    // 返回固定宽度(补前导零)的字符串,长度等于 m_digits
    std::string toFixedString() const {
        std::string s = toString();
        while (s.length() < (size_t)m_digits)
            s = "0" + s;
        return s;
    }

    // ---------- 获取内部状态 ----------
    uint64_t toUllong() const { return m_value; }
    uint64_t getMaxValue() const { return m_maxValue; }
    int getBase() const { return m_base; }
    int getDigits() const { return m_digits; }

private:
    int m_base;          // 基数,2~36
    int m_digits;        // 位数(即数字长度)
    uint64_t m_value;    // 实际存储的数值(0 到 m_maxValue-1)
    uint64_t m_maxValue; // base^digits,即模数
    uint64_t m_pows[64]; // m_pows[i] = base^i,用于快速取位

    // 检查两个对象是否具有相同的基数和位数,否则抛出异常
    void check_compatible(const CustomBaseNumber& other) const {
        if (m_base != other.m_base || m_digits != other.m_digits)
            throw std::invalid_argument("operands must have same base and digits");
    }
};

抽象数值数据结构说明

本文所提供的高精度整数、有理数、模意义矩阵以及线性基四类结构,均属于面向特定数域与代数运算的封装型数据结构。它们在底层存储上分别采用线性数组、二元组、二维网格以及一维主元数组,在运算定义上则完整模拟了算术公理、线性代数规则以及有限域向量空间的性质,构成了从整数精确计算、线性变换加速到异或空间优化的重要工具链。以下依次阐述其设计原理、接口功能、典型应用场景及扩展方向。

一、高精度整数(BigInt)

原理
BigInt 采用十进制位数组(倒序存储)与独立符号位的设计,每一位取值范围为 0—9,通过向量低位对齐实现自然进位。比较操作基于位数与高位字典序;加减法模拟竖式笔算,统一符号后按位处理进位与借位。乘法实现为自适应混合策略:当操作数位数低于阈值(32位)时使用竖式 O(n^2) 乘法,超过阈值则递归调用 Karatsuba 分治算法(O(n^{\log_2 3}) \approx O(n^{1.58})),通过 z_0 = a_0 b_0、z_1 = (a_0+a_1)(b_0+b_1)、z_2 = a_1 b_1 三次乘法替换四次乘法,配合移位操作 \text{shift\_left}(等价于乘以 10^m)完成结果合成。除法采用试商法,从最高位逐位下移,利用二分查找(0—9)确定当前位商值。

函数用途

算法用途
适用于任意长度整数的精确运算,突破原生 64 位整型的范围限制,广泛用于大数阶乘、高精度幂运算、密码学大整数模运算及组合计数(卡特兰数、斯特林数)等场景。Karatsuba 优化使其在千万级十进制位乘法中仍保持可观的性能。

扩展与衍生

二、有理数(Fraction)

原理
Fraction 以不可变(值语义)方式存储分子 num 与分母 den,底层采用 __int128 保证中间乘积不溢出(亦可替换为 BigInt 以彻底消除溢出风险)。约分操作 reduce 在构造与每次运算后自动调用,利用 std::gcd 求取最大公约数并归一化分母为正。四则运算直接依照分数运算法则:

\frac{a}{b} \pm \frac{c}{d} = \frac{ad \pm bc}{bd},\quad \frac{a}{b} \times \frac{c}{d} = \frac{ac}{bd},\quad \frac{a}{b} \div \frac{c}{d} = \frac{ad}{bc}.

比较运算则通过交叉相乘避免浮点数误差。

函数用途

算法用途
专用于需要绝对精确的数值场景,如物理常数有理逼近、计费系统中的比例分摊、博弈论中的混合策略概率、以及几何计算中的斜率与交点坐标,避免浮点舍入误差导致的逻辑判断错误。

扩展与衍生

三、模意义矩阵(Matrix)

原理
Matrix 以二维动态数组(vector<vector<int>>)存储元素,所有数值运算均在模 10^9+7 素数下进行,确保结果落于 int 范围内且避免负数。矩阵乘法采用三重循环 i,j,k 的标准实现,逐项累加并取模。配套的 qpow(矩阵快速幂)利用指数二进制分解,将乘方运算的时间复杂度优化至 O(\log b \cdot n^3)。单位矩阵通过 setIdentity 在对角线置 1 实现。

函数用途

算法用途
矩阵结构是线性递推优化的核心工具,例如利用矩阵快速幂在 O(\log n) 时间内计算斐波那契数列第 n 项、求解常系数齐次线性递推序列。此外广泛应用于图论中邻接矩阵的路径计数(A^k 表示长度为 k 的路径数)、动态规划的状态转移加速,以及 Markov 链的稳态分布求解。

扩展与衍生

四、线性基(Linear Basis)

线性基是 \mathbb{F}_2(二元域)上向量空间的一组基,用于压缩表示一组整数的所有异或组合。它将每个整数视为 \mathbb{F}_2 上的向量(位数为 L,通常 L=32 或 64),异或运算对应于向量加法。给定集合 S,其张成的子空间为

\operatorname{span}(S)=\left\{\bigoplus_{x\in T} x \;\middle|\; T\subseteq S\right\}.

线性基存储该空间的一组极大线性无关向量,并提供高效的插入、化简、最值查询与第 k 小查询。

数据结构定义

模板类 Basis<N> 使用 array<T, N+1> d 存储基向量,其中 d[i] 表示最高位(most significant bit)为 i 的基向量(若存在)。类型 T 根据 N 自动选择 unsigned int(N<32)或 unsigned long long(否则)。

插入操作(高斯消元构造阶梯形)

void insert(T val) {
    for (int i = N; i >= 0; --i) {
        if ((val >> i) & 1) {
            if (!d[i]) { d[i] = val; return; }
            else val ^= d[i];
        }
    }
}

原理:从高位到低位扫描,若 val 的第 i 位为 1,则尝试用 d[i] 消去该位。若 d[i] 为空,则将 val 存入并终止;否则执行 val ^= d[i],使得 val 的最高位严格降低(因为 d[i] 的最高位恰为 i)。该过程等价于对增广矩阵做行阶梯消元,最终所有非零 d[i] 的最高位互异,构成一组基。若 val 被消为 0,则说明原数可由已有基线性表示,空间秩不变。

不变量:每个非零 d[i] 的最高位为 i,且各最高位唯一。

化简为对角形(极简基)

void reduce() {
    for (int i = N; i >= 0; --i) {
        if (!d[i]) continue;
        for (int j = i-1; j >= 0; --j)
            if (d[i] & (1<<j)) d[i] ^= d[j];
    }
    // 收集非零基到 base 向量(按升序)
}

原理:从高到低处理,利用已对角化的低位基消去当前向量的所有低位,使得每个非零基向量仅在其最高位为 1,即 d[i] = 2^i。这一过程不改变张成的子空间,因为每次操作都是基向量的线性组合替换。化简后,基向量之间位互不重叠,便于后续第 k 小查询。

查询最大异或和

T query_max() {
    T res = 0;
    for (int i = N; i >= 0; --i)
        if ((res ^ d[i]) > res) res ^= d[i];
    return res;
}

正确性:贪心从高位到低位,若当前结果第 i 位为 0 且存在最高位为 i 的基,则异或该基使该位变为 1,且更高位不变,数值必然增大。重复此过程得到子空间中的最大值。

查询最小非零值

T query_min() {
    for (int i = 0; i <= N; ++i) if (d[i]) return d[i];
    return 0;
}

由于阶梯形基中最小非零基对应最低的最高位,任何非零线性组合的数值至少为该值,因此直接返回最低位的非零基即为最小正数。

查询第 k 小异或值

T query_rank(T k) {
    if (!k) return 0;
    if (!easy) reduce();
    if (k > (1 << base.size())) return -1;
    T res = 0; --k;
    for (size_t i = 0; i < base.size(); ++i)
        if (k & (1 << i)) res ^= base[i];
    return res;
}

原理:化简后的基为 2^{p_0}, 2^{p_1}, \dots, 2^{p_{r-1}}(p_0 < p_1 < \cdots < p_{r-1})。子空间中的每个元素唯一对应一个二进制系数向量 (b_0,\dots,b_{r-1}),其数值为 \sum b_i 2^{p_i}。由于 p_i 递增,该数值的大小顺序与系数向量所组成的二进制数 \sum b_i 2^i 的顺序完全一致。因此,第 k 小元素(从 0 开始计数)对应 k-1 的二进制展开,即 \bigoplus_{i: (k-1)_i=1} 2^{p_i}。若 k \ge 2^r,则超出空间大小,返回 -1。

时间复杂度:插入、查询最大/最小均为 O(N),化简为 O(N^2),第 k 小查询为 O(r)(r 为秩),空间 O(N)。

算法用途

扩展与衍生

CustomBaseNumber 是一个固定位宽、任意基数(2–36)的整数封装类,其内部采用 uint64_t 存储实际数值,并通过预计算的权值数组快速实现数位访问与移位操作。所有算术运算均在模 base^{digits} 的意义下进行,自动处理溢出回绕(wrap‑around),非常适合模拟数字电路中的寄存器行为、任意进制编码转换以及有限环上的计算任务。

设计原理

1. 数值表示与模运算

2. 溢出与进位行为

3. 负数的表示

一元取负运算符 operator-() 返回 M - v(若 v \neq 0),即模 M 下的加法逆元。例如在十进制两位(b=10, d=2,M=100)中,-5 \equiv 95。这使得减法运算可以统一转化为加法取模,无需额外处理符号。

4. 类型安全与兼容性

所有二元运算(+, -, *, /, %, 比较等)均要求两个操作数具有相同的基数 b 和位数 d,否则抛出 std::invalid_argument。这避免了不同进制或不同位宽之间的混合运算带来的歧义,同时确保模数一致,便于环论上的运算封闭性。

函数用途

类别 方法/操作 说明
构造与工厂 CustomBaseNumber(base, value, digits),fromUllong(value, base, digits),fromString(str, base, digits) 从整数、字符串或默认值构造对象。字符串支持 0-9, A-Z, a-z 字符,自动解析并取模。
数位访问 getDigit(pos),setDigit(pos, value),flipDigit(pos) 获取、设置或翻转(变为 b-1-\text{原值})指定位置的数字,范围检查严格。
移位 shiftLeft(n), shiftRight(n),operator<<, operator>> 及其复合赋值 按 b 的幂次移动,支持回绕(左移)与截断(右移)。
一元运算 operator-, operator+ 求加法逆元(模 M)和恒等操作。
二元运算 +, -, *, /, % 及复合赋值 在模 M 下执行四则运算。除法与取模为整数除法(向零截断),除零时抛出异常。
比较 ==, !=, <, >, <=, >= 先检查兼容性,再比较 m_value 的大小,即普通整数序,与模数无关。
类型转换 operator size_t, explicit operator bool 提供到 size_t 的隐式转换和到 bool 的显式转换。
I/O operator<<, operator>> 流式输入输出,输出为无前导零的进制字符串,输入自动按当前对象的基数和位数解析。
字符串转换 toString(),toFixedString() 返回普通数字字符串(如 "1A3"),或固定长度为 d 的补零字符串。
状态查询 toUllong(), getMaxValue(), getBase(), getDigits() 获取内部存储的数值、模数、基数与位数。

算法用途

1. 数字电路仿真

2. 任意基数编码与转换

3. 密码学与伪随机数生成

4. 定点数模拟

5. 组合数学中的循环计数

扩展与衍生

1. 有符号扩展

2. 动态位数

3. 更大进制的支持

4. 与高精度整数结合

5. 性能优化

6. 与线性基结合