跳到正文

算法·理论

【算法模板】高精度(施工ing)

YuKeWang约 2 分钟
原文

这是 2026年1月20日 存档的第 2 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年1月20日
收录
2026年1月20日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v3当前
  2. v2
  3. v1
C++
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i = a;i <= b;i++)
#define per(i,a,b) for(int i = a;i >= b;i--)
const int N = 5010;//位数
struct Node
{
	int a[N],len;
	Node()
	{
		len=1;
		memset(a,0,sizeof a);
	}
};
void output(Node x)//高精度输出
{
    per(i,x.len,1)
        cout<<x.a[i];
}
bool operator <(Node a,Node b)//高精度重载判断大小
{
	if(a.len!=b.len)return a.len<b.len;
    per(i,a.len,1)
        if(a.a[i]!=b.a[i])
            return a.a[i]<b.a[i];
	return 0;
}
Node operator *(Node a,int b)//高精度乘单精度重载
{
    Node c;
    c.len=a.len;
    rep(i,1,c.len)//先不进位
        c.a[i]=a.a[i]*b;
    rep(i,1,c.len)//进位
    {
        c.a[i+1]+=c.a[i]/10;
        c.a[i]%=10;
    }
    while(c.a[c.len+1]>0)//扩充位数
    {
        c.len++;
        c.a[c.len+1]+=c.a[c.len]/10;
        c.a[c.len]%=10;
	}
	return c;
}
Node operator /(Node a,int b)//高精度除单精度重载
{
	Node c;
	c.len=a.len;
	long long ret = 0;
    per(i,c.len,1)
	{
		c.a[i]=(a.a[i]+ret*10)/b;
		ret=(a.a[i]+ret*10)%b;
	}
	while(c.len>1&&c.a[c.len]==0)//缩减位数
		c.len--;
	return c;
}
int main()
{
    ios::sync_with_stdio(0);
    return 0;
}

未完待续(高精铺地锦乘法、高精除模高精、高精压位)