#define _CRT_SECURE_NO_WARNINGS /* 计算 a * b % p */ #include<algorithm> #include<cstdio> #include<cstring> #include<iostream> usingnamespace std; longlong a, b, p;
typedefunsignedlonglong ull; ull mul(ull a, ull b, ull p){ a %= p, b %= p; // 当a,b一定在0~p之间时,此行不必要 ull c = (longdouble)a * b / p; ull x = a * b, y = c * p; longlong ans = (longlong)(x % p) - (longlong)(y % p); if (ans < 0) ans += p; return ans; }
intmain(){ /* a: 8765432112345678 b: 8765432112953417 p: 87654321123456788 */ // freopen("./liyuds_cases/mul4.in", "r", stdin); a = 8765432112345678; b = 8765432112953417; p = 87654321123456788; // cin >> a >> b >> p; cout << mul(a, b, p) << endl; // correct answer is 54345679096057018, while here output is 15009041312430882 }
ull mul(ull a, ull b, ull p){ a %= p, b %= p; // 当a,b一定在0~p之间时,此行不必要 ull c = (longdouble)a * b / p; ull x = a * b; ull y = c * p; longlong ans = (longlong)(x % p) - (longlong)(y % p); if (ans < 0) ans += p; return ans; }
ll mul_v2(ll a, ll b, ll p){ ll ans = 0; while (b) { if (b & 1) ans = (ans + a) % p; a = a * 2 % p; b >>= 1; } return ans; }
intmain(){ ll p = (ll)87654321123456788; for (ll a = 8765432112345678; a < 87654321123456788; a++) { for (ll b = 8765432112345678; b < 87654321123456788; b++) { if (mul_v2(a, b, p) != mul(a, b, p)) { cout << "a => " << a << ", b => " << b << endl; cout << mul_v2(a, b, p) << ", " << mul(a, b, p) << endl; } } } }