支持long long
#include <algorithm> typedef long long ll; ll GCD(ll a, ll b) { return b ? GCD(b, a % b) : a; } ll MultiMod(ll a, ll b, ll n) { // a * b % n ll res = 0; MillarRabin a %= n; while (b > 0) { if (b & 1) { res += a; if (res >= n) res -= n; } a <<= 1; if (a >= n) a -= n; b >>= 1; } return res; } ll QuickMod(ll a, ll b, ll n) { // a ^ b % n ll res = 1; a %= n; while (b > 0) { if (b & 1) res = MultiMod(res, a, n); a = MultiMod(a, a, n); b >>= 1; } return res; } bool MillarRabin(ll n) { // 判断是否素数 if (n == 2 || n == 3 || n == 5 || n == 7 || n == 11) return true; if (n == 1 || !(n & 1) || !(n % 3) || !(n % 5) || !(n % 7) || !(n % 11)) return false; ll t = 0, m = n - 1, x, y; while (!(m & 1)) { m >>= 1; t++; } for (int i = 0; i < 10; i++) { ll a = rand() % (n - 2) + 2; x = QuickMod(a, m, n); for (ll j = 0; j < t; j++) { y = MultiMod(x, x, n); if (y == 1 && x != 1 && x != n - 1) return false; x = y; } if (y != 1) return false; } return true; }
时间: 2024-10-06 07:31:47