对于给定的两个一元二次方程,问使得L<=a1x1+b1==a2x2+b2<=R且x1,x2>=0的解一共有几个
比较容易看出来对于任意一个解X, X==b1(mod a1),X==b2(mod a2)
那么使用扩展欧几里得得到m0 a0
使得 任意k k*m0+a0都是一个可行解
现在问题就变成了 对于给定的区间L,R,L<=x*m0+a0<=R x的个数
又因为问题要求 x1,x2>=0 故我们需要处理左边界
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <string>
#include <cstring>
#include <string.h>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
using namespace std;
#define sp system("pause")
typedef long long ll;
typedef pair<int, int> pii;
ll extend_gcd(ll a, ll b, ll &x, ll &y)
{
if (a == 0 && b == 0)return -1;
if (b == 0){ x = 1; y = 0; return a; }
ll d = extend_gcd(b, a%b, y, x);
y -= a / b*x;
return d;
}
ll m[10], a[10];
bool solve(ll &m0, ll &a0, ll m, ll a)
{
ll y, x;
ll g = extend_gcd(m0, m, x, y);
if (abs(a - a0) % g)return false;
x *= (a - a0) / g;
x %= m / g;
a0 = (x*m0 + a0);
m0 *= (m / g);
a0 %= m0;
if (a0 < 0)a0 += m0;
return true;
}
bool MLES(ll &m0, ll &a0, int n)
{
bool flag = true;
m0 = 1; a0 = 1;
for (int i = 0; i < n; i++)
{
if (!solve(m0, a0, m[i], a[i]))
{
flag = false;
break;
}
}
return flag;
}
int main()
{
ll L, R; ll b1, b0;
cin >> m[0] >> a[0] >> m[1] >> a[1] >> L >> R;
b1 = a[1]; b0 = a[0];
if (a[1] < 0)
{
ll pl = (-a[1]) / m[1];
a[1] = (a[1] + (pl + 1)*m[1]) % m[1];
}
if (a[0] < 0)
{
ll pl = (-a[0]) / m[0];
a[0] = (a[0] + (pl + 1)*m[0]) % m[0];
}
ll m0, a0;
if (!MLES(m0, a0, 2))
{
puts("0");
return 0;
}
ll gao = max(b1, b0);
ll ans = 0;
L = max(L, gao);
if (L>R)
{
puts("0");
return 0;
}
ll pu = ceil((L - a0)*1.0 / m0);
if (L == pu*m0 + a0)ans++, pu++;
while (pu*m0 + a0 < L)pu++;
L = pu*m0 + a0;
if (L <= R)
{
ans++;
ans += (R - L) / m0;
}
printf("%I64d\n", ans);
}