Description
求在小于等于
的正整数中有多少个
满足:
Solution
扩展CRT模板题。
考虑将同余方程两两合并,对于:
我们将其转化成:
联立、整理得:
这个方程可以用扩欧来解。
将解出来的
带入
,求得
,则合并得到的方程为:
注意:这里的
为带入
求出来的值,
为方程的未知数!!
坑:注意处理 ,题目中要求的是正整数解, 不能算!!
Code
/************************************************
* Au: Hany01
* Date: May 27th, 2018
* Prob: [HDU1573] X问题
* Email: [email protected]
************************************************/
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
#define File(a) freopen(a".in", "r", stdin), freopen(a".out", "w", stdout)
#define rep(i, j) for (register LL i = 0, i##_end_ = (j); i < i##_end_; ++ i)
#define For(i, j, k) for (register LL i = (j), i##_end_ = (k); i <= i##_end_; ++ i)
#define Fordown(i, j, k) for (register LL i = (j), i##_end_ = (k); i >= i##_end_; -- i)
#define Set(a, b) memset(a, b, sizeof(a))
#define Cpy(a, b) memcpy(a, b, sizeof(a))
#define x first
#define y second
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define ALL(a) (a).begin(), (a).end()
#define SZ(a) ((int)(a).size())
#define INF (0x3f3f3f3f)
#define INF1 (2139062143)
#define Mod (1000000007)
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define y1 wozenmezhemecaia
template <typename T> inline bool chkmax(T &a, T b) { return a < b ? a = b, 1 : 0; }
template <typename T> inline bool chkmin(T &a, T b) { return b < a ? a = b, 1 : 0; }
inline LL read()
{
register LL _, __; register char c_;
for (_ = 0, __ = 1, c_ = getchar(); c_ < '0' || c_ > '9'; c_ = getchar()) if (c_ == '-') __ = -1;
for ( ; c_ >= '0' && c_ <= '9'; c_ = getchar()) _ = (_ << 1) + (_ << 3) + (c_ ^ 48);
return _ * __;
}
LL n, m, k, A, B, C, Gcd, t1, t2, ns;
struct Equation
{
LL c, m;
}Eq[13];
LL gcd(LL x, LL y, LL& a, LL& b)
{
if (!x) { a = 0, b = 1; return y; }
register LL ret = gcd(y % x, x, a, b),t = a;
a = b - a * (y / x);
b = t;
return ret;
}
int main()
{
#ifdef hany01
File("hdu1573");
#endif
for (static LL T = read(); T --; )
{
n = read(), m = read(), ns = 0;
For(i, 1, m) Eq[i].m = read();
For(i, 1, m) Eq[i].c = read();
Fordown(i, m, 2) {
A = Eq[i - 1].m, B = -Eq[i].m, C = Eq[i].c - Eq[i - 1].c;
if (C % (Gcd = __gcd(A, B))) { ns = 1; break; }
k = C / Gcd, gcd(A, B, t1, t2), t1 *= k, t2 *= k;
Eq[i - 1].c = t1 * Eq[i - 1].m + Eq[i - 1].c;
Eq[i - 1].m = Eq[i - 1].m * Eq[i].m / __gcd(Eq[i - 1].m, Eq[i].m);
}
((Eq[1].c %= Eq[1].m) += Eq[1].m) %= Eq[1].m;
if (ns || Eq[1].c > n) puts("0");
else printf("%lld\n", (n - Eq[1].c) / Eq[1].m + 1 + (Eq[1].c ? 0 : -1));
}
return 0;
}
//《淮上喜会梁川故人》
//韦应物
//江汉曾为客,相逢每醉还。
//浮云一别后,流水十年间。
//欢笑情如旧,萧疏鬓已斑。
//何因北归去,淮上对秋山。