跳到正文

个人记录

高精度库(BigInteger)

redghost约 16 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年11月9日
篇幅
约 16 分钟

版本

  1. v1当前

相信许多人因为高精度而感到麻烦,于是我便写了一个实用且高效的高进度库,废话不多说,直接上代码 Page Views Count

C++
/**#include <bint>
 * bint (BigInteger)
 * FileName			bint.c
 * E-Mail:			qq_2136257812@163.com
 * Blog:			https://www.luogu.com.cn/blog/redghost233/
 *
 * 使用本库,必须用C++编译,可支持的编译器:
 * VC6/VC2008/VC2010/VC2012/VC2013/MinGW3.4.5/MinGW4.7.1/MinGW4.8.1
 */
#include <iostream>
#include <vector>
#include <string>
#include <sstream>

// #define bint BigInteger

class BigInteger
{
private:
	std::vector<__int16> digits; // 用于存储大整数的每一位数字
	bool isNegative;			// 用于标识是否为负数

public:
	// 构造函数,初始化大整数
	BigInteger(const char *charNum)
	{
		*this = std::string(charNum);
	}

	BigInteger(const std::string &strNum)
	{
		if (strNum[0] == '-')
		{
			isNegative = true;
			// 从索引1开始读取数字
			for (int i = strNum.size() - 1; i > 0; --i)
			{
				digits.push_back(strNum[i] - '0');
			}
		}
		else
		{
			isNegative = false;
			for (int i = strNum.size() - 1; i >= 0; --i)
			{
				digits.push_back(strNum[i] - '0');
			}
		}
	}

	BigInteger() : isNegative(false) {}

	BigInteger(long long num)
	{
		if (num >= 0)
			isNegative = false;
		else
			isNegative = true, num = -num;
		if (num == 0)
			digits.push_back(0);
		while (num > 0)
		{
			digits.push_back(num % 10);
			num /= 10;
		}
	}
	BigInteger(int num)
	{
		if (num >= 0)
			isNegative = false;
		else
			isNegative = true, num = -num;
		if (num == 0)
			digits.push_back(0);
		while (num > 0)
		{
			digits.push_back(num % 10);
			num /= 10;
		}
	}

	// 平均数函数
	BigInteger average(const BigInteger &x, const BigInteger &y)
	{
		BigInteger result = x + y;
		for (int i = result.digits.size(); i >= 1; i--)
		{
			result.digits[i - 1] += result.digits[i] % 2 * 10;
			result.digits[i] /= 2;
		}
		result.digits[0] /= 2;
		// 移除前导零
		result.normalize();

		return result;
	}
	// 开平方函数
	BigInteger sqrt()
	{
		if (*this < 0)
			throw std::runtime_error("Cannot compute square root of a negative number");
		if (*this == 0 || *this == 1)
			return *this;

		BigInteger low = 0;
		BigInteger high = *this;
		BigInteger result;

		while (low <= high)
		{
			BigInteger mid = average(low, high);
			BigInteger squared = mid * mid;
			if (squared == *this)
			{
				return mid; // 找到精确的平方根
			}
			else if (squared < *this)
			{
				low = mid + 1;
				result = mid; // 更新结果为当前的中间值
			}
			else
			{
				high = mid - 1;
			}
		}
		return result;
	}
	// 重载运算符>>
	friend std::istream &operator>>(std::istream &in, BigInteger &num)
	{
		std::string input;
		in >> input;
		num = BigInteger(input);
		return in;
	}

	// 重载运算符<<
	friend std::ostream &operator<<(std::ostream &out, const BigInteger &num)
	{
		if (num.isNegative)
		{
			out << '-';
		}
		for (int i = num.digits.size() - 1; i >= 0; --i)
		{
			out << num.digits[i];
		}
		return out;
	}

	// 重载正负号
	BigInteger operator-(void) const
	{
		BigInteger neg = *this;
		neg.isNegative = !neg.isNegative;
		return neg;
	}

	// 重载 < 运算符
	bool operator<(const BigInteger &other) const
	{
		if (isNegative != other.isNegative)
		{
			return isNegative;
		}

		if (digits.size() != other.digits.size())
		{
			return (digits.size() < other.digits.size()) ^ isNegative;
		}

		for (int i = digits.size() - 1; i >= 0; --i)
		{
			if (digits[i] != other.digits[i])
			{
				return (digits[i] < other.digits[i]) ^ isNegative;
			}
		}

		return false; // 相等
	}

	// 重载 > 运算符
	bool operator>(const BigInteger &other) const
	{
		return other < *this;
	}

	// 重载 <= 运算符
	bool operator<=(const BigInteger &other) const
	{
		return !(*this > other);
	}

	// 重载 >= 运算符
	bool operator>=(const BigInteger &other) const
	{
		return !(*this < other);
	}

	// 重载 == 运算符
	bool operator==(const BigInteger &other) const
	{
		return !(*this > other) && !(*this < other);
	}

	// 重载 != 运算符
	bool operator!=(const BigInteger &other) const
	{
		return *this > other || *this < other;
	}

	// 加法操作
	BigInteger operator+(const BigInteger &other) const
	{
		if (isNegative != other.isNegative)
		{
			return *this - (-other);
		}

		BigInteger result;
		result.digits.resize(std::max(digits.size(), other.digits.size()) + 1, 0);
		int carry = 0;

		for (size_t i = 0; i < result.digits.size(); ++i)
		{
			int sum = carry;
			if (i < digits.size())
			{
				sum += digits[i];
			}
			if (i < other.digits.size())
			{
				sum += other.digits[i];
			}

			result.digits[i] = sum % 10;
			carry = sum / 10;
		}

		// 移除前导零
		result.normalize();

		result.isNegative = isNegative;
		return result;
	}

	BigInteger &operator+=(const BigInteger &other)
	{
		*this = *this + other;
		return *this;
	}

	// 减法操作
	BigInteger operator-(const BigInteger &other) const
	{
		if (isNegative != other.isNegative)
		{
			return *this + (-other);
		}
		if (this->abs() < other.abs())
		{
			return -(other - *this);
		}

		BigInteger result;
		result.digits.resize(digits.size(), 0);

		for (size_t i = 0; i < result.digits.size(); ++i)
		{
			if (i < digits.size())
			{
				result.digits[i] += digits[i];
			}
			if (i < other.digits.size())
			{
				result.digits[i] -= other.digits[i];
			}
			if (result.digits[i] < 0)
			{
				--result.digits[i + 1];
				result.digits[i] += 10;
			}
		}

		// 移除前导零
		result.normalize();

		result.isNegative = isNegative;
		return result;
	}

	BigInteger &operator-=(const BigInteger &other)
	{
		*this = *this - other;
		return *this;
	}

	// 乘法操作
	BigInteger operator*(const BigInteger &other) const
	{
		BigInteger result;
		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 cur = result.digits[i + j] + digits[i] * 1LL * (j < other.digits.size() ? other.digits[j] : 0) + carry;
				result.digits[i + j] = static_cast<int>(cur % 10);
				carry = static_cast<int>(cur / 10);
			}
		}

		// 移除前导零
		result.normalize();

		result.isNegative = isNegative != other.isNegative;
		return result;
	}

	BigInteger &operator*=(const BigInteger &other)
	{
		*this = *this * other;
		return *this;
	}

	// 除法操作
	BigInteger operator/(const BigInteger &divisor)
	{
		if (divisor == 0)
		{
			throw std::runtime_error("Division by zero");
		}

		BigInteger result = 0, rest = 0;
		for (long long i = digits.size() - 1; i >= 0; --i)
		{
			rest = (rest << 1) + digits[i];
			int b = 0;
			while (rest >= divisor.abs())
			{
				++b;
				rest -= divisor.abs();
			}
			result = (result << 1) + b;
		}

		result.isNegative = isNegative ^ divisor.isNegative;
		return result;
	}

	// mod 操作
	BigInteger operator%(const BigInteger &divisor)
	{
		if (divisor == 0)
		{
			throw std::runtime_error("Modulo by zero");
		}

		BigInteger rest = 0;
		for (long long i = digits.size() - 1; i >= 0; --i)
		{
			rest = (rest << 1) + digits[i];
			while (rest >= divisor.abs())
			{
				rest -= divisor.abs();
			}
		}

		rest.isNegative = isNegative;

		return rest;
	}

	// 左位移运算
	BigInteger operator<<(long long shift) const
	{
		if (shift <= 0)
		{
			throw std::runtime_error("Non-positive shift value");
		}
		else
		{
			BigInteger result = *this;
			result.digits.insert(result.digits.begin(), shift, 0); // 在数字的前面插入shift个0
			return result;
		}
	}

	// 右位移运算
	BigInteger operator>>(long long shift) const
	{
		if (shift <= 0)
		{
			throw std::runtime_error("Non-positive shift value");
		}
		else
		{
			if ((size_t)shift >= this->digits.size())
			{
				return BigInteger(0);
			}
			else
			{
				BigInteger result = *this;
				result.digits.erase(result.digits.begin(), result.digits.begin() + shift); // 移除前面的shift位数字
				return result;
			}
		}
	}

	// 移除前导零
	BigInteger &normalize()
	{
		while (digits.size() > 1 && digits.back() == 0)
		{
			digits.pop_back();
		}
		return *this;
	}

	// 绝对值函数
	BigInteger abs() const
	{
		BigInteger absNum = *this;
		absNum.isNegative = false;
		return absNum;
	}
};

啊啊啊,我搞了一周才写完,可以支持一下吗?

Tip

像正常的类型一样使用就行了。

更新日志

2023年11月26日

修复了减法的部分情况出错,优化了除法与mod算法

原文