BigInteger 扩展
这是我写的一个高精度扩展库,兼容 BigInteger 2。
涉及到大整数 时,记 是 的位数。
| 函数 | 功能 | 时间复杂度 | 空间复杂度 |
|---|---|---|---|
random_big(n, flag, seed) | 生成位数为 的随机大整数, 表示是否为正数, 为随机种子 | ||
factorial(n) | 计算 | ||
isprime(x) | 判断 是否为素数 | ||
inverse(x, p) | 求 模 意义下的乘法逆元 |
#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