Codeforces 710 D. Arithmetic progressions

Source: Internet
Author: User


\ (x=a_1k+b_1=a_2l+b_2,l\leqslant x \leqslant r\) the number of \ (x\) that satisfies such conditions.


Expand Euclid + Chinese remainder theorem.

Find this equivalent to a linear equation set.

\ (x \equiv b_1 (mod a_1) \)

\ (x \equiv b_2 (mod a_2) \)

Subtract from the original two (a_1k-a_2l=b_2-b_1\)

This is used to expand Euclid to seek, if \ ((a_1,a_2) \nmid (b_2-b_1) \) obviously no solution.

The equation used to expand Euclid is \ (a_1k-a_2l= (a_1,a_2) \), and multiply the equation by \ (\frac{b_2-b_1}{(a_1,a_2)}\)

Now we have a set of legal solutions, the general solution is \ (K=k_0+\frac {a_2}{(a_1,a_2)},l=l_0-\frac {a_1}{(a_1,a_2)}\)

The minimum positive solution can be modeled on \ (\frac {a_2}{(a_1,a_2)}\).

Then the solution number of the original equation is \ (k+n[a_1,a_2]\), do not forget to calculate this value of the endpoint.

#include <cstdio> #include <algorithm> #include <iostream>using namespace std;typedef long Long ll;# Define Debug (a) cout<< #a << "=" <<a<< "ll a1,b1,a2,b2,k,l,x,lcm,gcd,l,r,ans;void exgcd (ll A,ll B,ll &x,ll &y) {if (!b) {X=1,y=0;return;} EXGCD (B,a%b,x,y); LL t=x;x=y,y=t-(A/b) *y;} int main () {Ios::sync_with_stdio (false);cin>>a1>>b1>>a2>>b2>>l>>r; EXGCD (a1,a2,k,l); GCD=__GCD (A1,A2), LCM=A1/GCD*A2; L=max (L,max (B1,B2)); if (b2-b1)%GCD | | L>r) return puts ("0"), 0;k*= (B2-B1)/gcd,k= (k% (A2/GCD) +a2/gcd)% (A2/GCD), X=a1*k+b1;//debug (x), Debug (LCM), Debug (L ), Debug (R), if (r>=x) ans+= (r-x)/lcm+1;if (l-1>=x) ans-= (l-1-x)/lcm+1;cout<<ans<<endl;return 0;}


Codeforces 710 D. Arithmetic progressions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.