跳到正文

剪贴板

剪贴板 9b0les2j

原文
剪贴板信息

剪贴板信息

收录
更新

BigInteger 扩展

这是我写的一个高精度扩展库,兼容 BigInteger 2。

涉及到大整数 xx 时,记 nn 是 xx 的位数。

函数功能时间复杂度空间复杂度
random_big(n, flag, seed)生成位数为 nn 的随机大整数,flagflag 表示是否为正数,seedseed 为随机种子O(n)O(n)O(n)O(n)
factorial(n)计算 n!n!O(n2log⁡n)O(n^2 \log n)O(n2)O(n^2)
isprime(x)判断 xx 是否为素数O(10n2nlog⁡n)O(10^{\frac{n}{2}} n \log n)O(nw)O(\dfrac{n}{w})
inverse(x, p)求 xx 模 pp 意义下的乘法逆元O(nlog⁡n)O(n \log n)O(nw)O(\dfrac{n}{w})
C++
#ifndef BIGINTEGER_EXT_H
#define BIGINTEGER_EXT_H

#include <random>
#include "BigInteger.hpp"   // 这里是BigInteger类相关代码

inline BigInteger random_big(const int&, bool = true, const unsigned& = 0);
inline BigInteger factorial(const int&);
inline bool isprime(const BigInteger&);
inline BigInteger inverse(const BigInteger&, const BigInteger&);

inline BigInteger random_big(const int& n, bool flag, const unsigned& seed) {
	static std::default_random_engine e;
	static std::uniform_int_distribution<unsigned> u(0, 9);
	std::string s;
	if (seed != 0) e.seed(seed);
	if (!flag) s.push_back('-');
	int t = u(e);
	while (t == 0) t = u(e);
	s.push_back(t ^ 48);
	for (long i = 2; i <= n; i++) s.push_back(u(e) ^ 48);
	return s;
}

inline BigInteger factorial(const int& n) {
	BigInteger res = 1;
	for (int i = 2; i <= n; i++) res *= i;
	return res;
}

inline bool isprime(const BigInteger& x) {
	if (x <= 1) return false;
	if (x == 2 || x == 3) return true;
	BigInteger t = x % 6;
	if (t != 1 && t != 5) return false;
	for (BigInteger i = 5; i * i <= x; i += 6) {
		if (x % i == 0 || x % (i + 2) == 0) return false;
	}
	return true;
}

void __exgcd(const BigInteger& a, const BigInteger& b, BigInteger& x, BigInteger& y) {
	if (b == 0) return x = 1, y = 0, void();
	__exgcd(b, a % b, y, x);
	y -= a / b * x;
}
inline BigInteger inverse(const BigInteger& x, const BigInteger& p) {
	BigInteger a, b;
	__exgcd(x, p, a, b);
	return (a % p + p) % p;
}

#endif //BIGINTEGER_EXT_H