Educational Codeforces Round 16 D. Two Arithmetic Progressions (不互质中国剩余定理)

Two Arithmetic Progressions

题目链接:

http://codeforces.com/contest/710/problem/D

Description


You are given two arithmetic progressions: a1k + b1 and a2l + b2. Find the number of integers x such that L ≤ x ≤ R and x = a1k' + b1 = a2l' + b2, for some integers k', l' ≥ 0.

Input


The only line contains six integers a1, b1, a2, b2, L, R (0 < a1, a2 ≤ 2·109,  - 2·109 ≤ b1, b2, L, R ≤ 2·109, L ≤ R).

Output


Print the desired number of integers x.

Sample Input

2 0 3 3 5 21
2 4 3 0 6 17

Sample Output

3
2


题意:


求[L,R]区间内有多少个整数y满足 y = k1x1+b1 且 y = k2x2+b2. (x1 x2 >= 0)


题解:


首先把两条直线画到平面上,题目限制了直线斜率都大于零. 又由于 x1 x2 >= 0.
所以y的区间可以进一步限制为 [max(L, max(b1,b2)), R];
问题就变为在这个新区间里找使得两个式子相等的"整点"个数了.
这里可以把两个式子通过拓展中国剩余定理(因为不互质)合并成一个式子, 然后计算区间内的解的个数即可.
注意:可能两式子不能合并,直接输出0; 正确计算区间内的解的个数(见注释).


比赛做的时候只想到了拓展中国剩余定理这里,然后想的是b不一定小于k所以不算是模方程,以为不能做.
实际上(拓展)中国剩余定理在处理同余模方程组的时候不要求余数小于模数.


代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <vector>
#include <list>
#define LL long long
#define eps 1e-8
#define maxn 10000100
#define mod 100000007
#define inf 0x3f3f3f3f3f3f3f3f
#define mid(a,b) ((a+b)>>1)
#define IN freopen("in.txt","r",stdin);
using namespace std;

LL x,y,gcd;
void ex_gcd(LL a,LL b)
{
    if(!b) {x=1;y=0;gcd=a;}
    else {ex_gcd(b,a%b);LL temp=x;x=y;y=temp-a/b*y;}
}

LL n,m[2],a[2];    //x%m=a
LL cur, T;
/*模线性方程组--不互质中国剩余定理*/
int ex_China() {
    LL m1,m2,n1,n2,x0;
    m1=m[0];n1=a[0];

    for(int i=1; i<n; i++)
    {
        m2=m[i];
        n2=a[i];
        ex_gcd(m1,m2);
        if((n2-n1)%gcd) return -1;
        LL tmp=m2/gcd;
        x0=(x*((n2-n1)/gcd)%tmp+tmp)%tmp;

        n1=n1+x0*m1;
        m1=m1/gcd*m2;
    }
    n1=(n1+m1)%m1;

    cur = n1; T = m1;
    return T;
}


int main(int argc, char const *argv[])
{
    //IN;

    n = 2;
    cin >> m[0] >> a[0] >> m[1] >> a[1];
    LL L,R; cin >> L >> R;
    L = max(max(a[0], a[1]), L);

    int ret = ex_China();

    LL ans = 0;
    if(ret == -1) { /*特判不能合并的方程组*/
        printf("0\n");
        return 0;
    }

    if(cur >= L) {  /*找一个合适的起点,分别计算L-1和R到这个点之间有多少个解*/
        cur -= ((cur-L)/T + 1) * T;
    }

    if(L <= R) {
        ans = (R - cur) / T - (L - 1 - cur) / T;
    }

    printf("%I64d\n", ans);

    return 0;
}

转载于:https://www.cnblogs.com/Sunshine-tcf/p/5801347.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值