数学数据结构
高精度
//@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位)时使用竖式
函数用途
- 构造函数支持从
long long、十进制字符串及默认零值构造,并自动去除前导零。 - 关系运算符(
==、<等)兼顾符号与绝对值大小;算术运算符(+、-、*、/、%)均正确处理异号情形,且除法与取模对除零进行异常保护。 abs()返回绝对值副本;is_zero()快速判零。
算法用途
适用于任意长度整数的精确运算,突破原生 64 位整型的范围限制,广泛用于大数阶乘、高精度幂运算、密码学大整数模运算及组合计数(卡特兰数、斯特林数)等场景。Karatsuba 优化使其在千万级十进制位乘法中仍保持可观的性能。
扩展与衍生
- 可将进制提升至
10^9 或2^{32} (压位高精),大幅降低向量长度与循环次数,提升常数效率。 - 可将
long long基类型替换为自定义模数类型,实现模意义下的高精度运算,服务于 NTT(数论变换)前的整数预处理。 - 可与
Fraction结构结合,构建无精度损失的任意精度有理数类。
二、有理数(Fraction)
原理
Fraction 以不可变(值语义)方式存储分子 num 与分母 den,底层采用 __int128 保证中间乘积不溢出(亦可替换为 BigInt 以彻底消除溢出风险)。约分操作 reduce 在构造与每次运算后自动调用,利用 std::gcd 求取最大公约数并归一化分母为正。四则运算直接依照分数运算法则:
比较运算则通过交叉相乘避免浮点数误差。
函数用途
- 构造函数接受整数、分子分母对,自动执行约分。
- 重载全部算术与关系运算符,支持类原生数值的操作体验。
asImproper()与asMixed()分别输出假分数(分子/分母)及带分数(整数部分 + 真分数部分),便于人机交互或结果格式化。
算法用途
专用于需要绝对精确的数值场景,如物理常数有理逼近、计费系统中的比例分摊、博弈论中的混合策略概率、以及几何计算中的斜率与交点坐标,避免浮点舍入误差导致的逻辑判断错误。
扩展与衍生
- 将
FractionInt从__int128替换为前述BigInt,可获得任意分母长度的超大有理数,适用于符号计算系统。 - 可添加
toDouble()方法用于最终结果的可视化展示,并内置舍入模式(向上、向下、四舍五入)以适配不同财务规范。 - 支持连分数展开,用于求解佩尔方程或最佳有理逼近。
三、模意义矩阵(Matrix)
原理
Matrix 以二维动态数组(vector<vector<int>>)存储元素,所有数值运算均在模 int 范围内且避免负数。矩阵乘法采用三重循环 qpow(矩阵快速幂)利用指数二进制分解,将乘方运算的时间复杂度优化至 setIdentity 在对角线置 1 实现。
函数用途
- 构造函数指定行列,默认零初始化。
operator*验证左列等于右行,执行乘法并返回新矩阵;不匹配时返回空矩阵(0×0)以作错误标记。- 流运算符(
>>、<<)支持便捷输入输出,输入时自动对元素取模。 - 全局函数
qpow计算矩阵的整数幂;sum快速求矩阵所有元素之和。
算法用途
矩阵结构是线性递推优化的核心工具,例如利用矩阵快速幂在
扩展与衍生
- 支持稀疏矩阵存储(如三元组表、CSR 格式),在大规模图计算中节省内存与计算量。
- 可增加Strassen 分块乘法算法(
O(n^{2.81}) ),进一步优化稠密矩阵乘法的大规模性能。 - 引入高斯消元与行列式计算方法,可直接用于求解线性方程组及矩阵求逆(需扩展模逆元支持)。
- 结合
Fraction作为元素类型,可实现无精度损失的线性代数求解器。
四、线性基(Linear Basis)
线性基是
线性基存储该空间的一组极大线性无关向量,并提供高效的插入、化简、最值查询与第
数据结构定义
模板类 Basis<N> 使用 array<T, N+1> d 存储基向量,其中 d[i] 表示最高位(most significant bit)为 T 根据 unsigned int(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 的第 d[i] 消去该位。若 d[i] 为空,则将 val 存入并终止;否则执行 val ^= d[i],使得 val 的最高位严格降低(因为 d[i] 的最高位恰为 d[i] 的最高位互异,构成一组基。若 val 被消为 0,则说明原数可由已有基线性表示,空间秩不变。
不变量:每个非零 d[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,即
查询最大异或和
T query_max() {
T res = 0;
for (int i = N; i >= 0; --i)
if ((res ^ d[i]) > res) res ^= d[i];
return res;
}
正确性:贪心从高位到低位,若当前结果第
查询最小非零值
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;
}
原理:化简后的基为
时间复杂度:插入、查询最大/最小均为
算法用途
- 最大异或和:给定若干数,选任意子集使异或和最大(经典问题)。
- 第
k 小异或和:求所有子集异或值中第k 小的数。 - 判断元素是否存在:尝试插入某数,若被消为 0 则表示可由原集合异或得到。
- 图论环空间:无向图中利用 DFS 生成树构造返祖边对应的环的线性基,可快速求解图中异或和最大的路径(如「XOR 最长路径」问题)。
- 编码理论:线性基本质上是线性分组码的生成矩阵的压缩形式,用于纠错码设计与分析。
扩展与衍生
- 动态线性基:支持删除元素(需维护每个基向量的出现次数)或离线分治。
- 合并线性基:将两个基合并只需将其中一个的所有元素插入另一个,复杂度
O(N^2) 。 - 扩展到任意有限域:可将异或替换为模
p 加法,实现GF(p) 上的线性基。 - 查询第
k 大:可由最大值与第k 小配合得到。 - 求线性基的秩:即非零基的个数,直接返回
base.size()。五、进制数(CustomBaseNumber)
CustomBaseNumber 是一个固定位宽、任意基数(2–36)的整数封装类,其内部采用 uint64_t 存储实际数值,并通过预计算的权值数组快速实现数位访问与移位操作。所有算术运算均在模
设计原理
1. 数值表示与模运算
-
设基数为
b (2 \le b \le 36 ),位数为d (1 \le d \le 64 ),则类维护一个无符号整数v (即m_value),满足0 \le v < M ,其中M = b^d 为模数(
m_maxValue)。任意运算结果均等价于在整数环\mathbb{Z}/M\mathbb{Z} 上的对应操作,即:v_{\text{result}} \equiv f(v_1, v_2, \dots) \pmod M. -
预计算权值数组
m_pows[i] = b^i(0 \le i < d ),用于快速获取/修改某一位的数字。第i 位(0 为最低位)的数字可表示为:\text{digit}_i = \left\lfloor \frac{v}{b^i} \right\rfloor \bmod b.
2. 溢出与进位行为
- 构造时若
value超出[0, M-1] ,则自动取模v = value \bmod M ,保证初始状态合法。 - 加减乘除、移位、自增自减等运算均以模
M 方式执行,不抛出溢出异常,而是静默回绕(例如M-1 + 1 \to 0 ),与无符号整数的自然溢出语义一致。 - 移位运算直接通过权值相乘或整除实现:
- 左移
n 位:v \leftarrow (v \cdot b^n) \bmod M ; - 右移
n 位:v \leftarrow \lfloor v / b^n \rfloor (高位补零,无回绕)。
- 左移
3. 负数的表示
一元取负运算符 operator-() 返回
4. 类型安全与兼容性
所有二元运算(+, -, *, /, %, 比较等)均要求两个操作数具有相同的基数 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) |
获取、设置或翻转(变为 |
| 移位 | shiftLeft(n), shiftRight(n),operator<<, operator>> 及其复合赋值 |
按 |
| 一元运算 | operator-, operator+ |
求加法逆元(模 |
| 二元运算 | +, -, *, /, % 及复合赋值 |
在模 |
| 比较 | ==, !=, <, >, <=, >= |
先检查兼容性,再比较 m_value 的大小,即普通整数序,与模数无关。 |
| 类型转换 | operator size_t, explicit operator bool |
提供到 size_t 的隐式转换和到 bool 的显式转换。 |
| I/O | operator<<, operator>> |
流式输入输出,输出为无前导零的进制字符串,输入自动按当前对象的基数和位数解析。 |
| 字符串转换 | toString(),toFixedString() |
返回普通数字字符串(如 "1A3"),或固定长度为 |
| 状态查询 | toUllong(), getMaxValue(), getBase(), getDigits() |
获取内部存储的数值、模数、基数与位数。 |
算法用途
1. 数字电路仿真
- 在硬件描述语言或逻辑模拟中,寄存器、计数器、算术逻辑单元(ALU)通常具有固定位宽且溢出回绕。
CustomBaseNumber可直接模拟这些行为,尤其支持非二进制基数(如 BCD 编码、八进制地址总线),为高级综合提供易用的数值模型。
2. 任意基数编码与转换
- 可用于进制转换工具的内部表示,例如将十进制数转换为 36 进制字符串,或解析 16 进制颜色码。配合
fromString与toString,可快速实现任意基数的互转。 - 固定位宽特性使其适用于哈希、校验码等需要固定长度输出的场景(如 Base32 编码的固定长度填充)。
3. 密码学与伪随机数生成
- 线性同余生成器(LCG)等算法通常需要对
2^k 取模,而CustomBaseNumber允许自定义模数(非 2 的幂),可用于构造模b^d 下的线性同余序列,拓宽随机数的分布特性。 - 其内置的乘法与加法取模操作可用于有限环上的散列函数或加密算法的轮函数(如 IDEA 中的乘法逆元运算可推广至其他模数)。
4. 定点数模拟
- 将小数部分映射到固定位数(例如低
k 位表示小数),利用移位与取模可实现高效的定点数加减乘除,且溢出可控,适用于嵌入式系统中的数值计算原型验证。
5. 组合数学中的循环计数
- 在环形缓冲、循环队列或时间轮算法中,索引需在
[0, M-1] 内循环递增/递减。operator++与operator--天然支持这种模循环,且任意基数的循环周期可自定义。
扩展与衍生
1. 有符号扩展
- 当前类仅支持无符号模运算。可添加符号位,或定义“有符号补码”视图:约定当
v \ge M/2 时视为负数(- (M-v) ),并添加toSignedInt()方法。这对于模拟计算机中的有符号整数溢出行为非常有用。
2. 动态位数
- 当前位数在构造时固定。可引入
resize(newDigits)方法,调整位数并重新计算模数,同时处理高位截断或零扩展,实现类似动态位宽的灵活计算。
3. 更大进制的支持
- 目前进制限制为 2–36。若要支持 64、256 等进制,可将数字字符集扩展(如使用 Unicode 或自定义码表),并将
m_pows数据类型改为__int128或BigInt以避免溢出。这将使类可用于 Base64 编码或大整数压缩表示。
4. 与高精度整数结合
- 将内部
m_value类型替换为BigInt,同时将m_pows存储为BigInt数组,即可构建任意位数、任意基数的大整数模运算类,适用于密码学中大数模幂运算(如 RSA 中的模乘),且无需担心位宽不足导致的溢出。
5. 性能优化
- 针对特定基数(如
b=2 或b=2^k ),可对移位和数位访问进行位运算加速,并减少除法取模次数。 - 对于频繁进行的模乘运算,可预先计算 Montgomery 常数,引入 Montgomery 模乘算法,进一步提升大模数下的乘法效率。
6. 与线性基结合
-
若将每个数位视为一个独立维度,则
b 进制数可看作向量空间\mathbb{Z}_b^d 上的元素。结合线性基思想,可构造任意有限环上的线性基,用于求解模b 意义下的线性方程组或最大线性无关组,拓展线性基的应用范围。