首页 > 其他 > 详细

高精度模板

时间:2021-06-14 23:39:37      阅读:38      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 10100
using namespace std;
const int base = 10;
struct Num {
	int num[N], len;
	Num(){ memset(num, 0, sizeof(num)); len = 0; }
	inline void Print() {
		for (int i = len - 1; ~i; --i) printf("%d", num[i]);
		puts("");
	}
};
inline bool cmp(const Num &a, const Num &b) {//a < b
	if (a.len != b.len) return a.len < b.len;
	for (int i = a.len - 1; ~i; --i) if (a.num[i] != b.num[i])
		return a.num[i] < b.num[i];
	return false;
}
inline Num operator +(const Num &a, const int b) {
	Num c;
	int len = a.len, r = b;
	for (int i = 0; i < len; ++i) {
		r += a.num[i];
		c.num[i] = r % base;
		r /= base;
	}
	while (r) c.num[len++] = r % base, r /= base;
	c.len = len;
	return c;
}
inline Num operator +(const Num &a, const Num &b) {
	Num c;
	int len = max(a.len, b.len);
	for (int i = 0; i < len; ++i) {
		c.num[i] = c.num[i] + a.num[i] + b.num[i];
		if (c.num[i] >= base) ++c.num[i + 1], c.num[i] -= base;
	}
	if (c.num[len]) ++len;
	c.len = len;
	return c;
}
inline Num operator -(const Num &a, const Num &b) {//a > b, return a - b
	Num c;
	int len = a.len;
	for (int i = 0; i < len; ++i) {
		c.num[i] = (c.num[i] + a.num[i] - b.num[i]);
		if (c.num[i] < 0) --c.num[i + 1], c.num[i] += base;
	}
	while (len && !c.num[len - 1]) --len;
	c.len = len;
	return c;
}
inline Num operator *(const Num &a, const int b) {
	Num c = a;
	if (!b) return Num();
	int r = 0, len = a.len;
	for (int i = 0; i < len; ++i) {
		r = (r + a.num[i] * b);
		c.num[i] = r % base;
		r /= base;
	}
	while (r) c.num[len++] = r % base, r /= base;
	c.len = len;
	return c;
}
inline Num operator /(const Num &a, const int b) {
	Num c;
	int r = 0, len = a.len;
	for (int i = len - 1; ~i; --i) {
		r = r * base + a.num[i];
		c.num[i] = r / b;
		r %= b;
	}
	while (len && !c.num[len]) --len;
	c.len = len;
	return c;
}
inline Num operator <<(const Num &a, const int b) {
	Num c;
	int len = a.len;
	for (int i = len - 1; ~i; --i) c.num[i + b] = a.num[i];
	c.len = len + b;
	return c;
}
int main() {
	Num jzp;
	jzp = jzp * 21323 + 1213;
	jzp = jzp * 123 + 4123;
	jzp = jzp << 3;
	jzp.Print();
	Num zzz;
	zzz = zzz + 2145123;
	zzz = zzz * 4213;
	zzz = zzz << 5;
	zzz.Print();
	(zzz - jzp).Print();
	return 0;
}

高精度模板

原文:https://www.cnblogs.com/JiaZP/p/14883393.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!