1295D - Same GCDs - CodeForces Solution


math number theory *1800

Please click on ads to support us..

C++ Code:

#include <cstdio>

#include <iostream>

#include <cstring>

#include <algorithm>

#include <vector>

#define PB push_back

#define MP make_pair

#define PII pair<int,int>

#define FIR first

#define SEC second

#define ll long long

using namespace std;

template <class T>

inline void rd(T &x) {

	x=0; char c=getchar(); int f=1;

	while(!isdigit(c)) { if(c=='-') f=-1; c=getchar(); }

	while(isdigit(c)) x=x*10-'0'+c,c=getchar(); x*=f;

}

ll gcd(ll a,ll b) { return b?gcd(b,a%b):a; }

int pri[100010],num,d[100010];

void getpri(int n) {

    for(int i=2;i<=n;++i) {

        if(!d[i]) pri[d[i]=++num]=i;

        for(int j=1;j<=d[i]&&i*(ll)pri[j]<=n;++j)

            d[i*pri[j]]=j;

    }

}

vector<ll> fac;

ll cal(ll L,ll R,ll n) {

    for(int j=1;j<=num&&pri[j]*(ll)pri[j]<=n;++j) if(n%pri[j]==0) {

        while(n%pri[j]==0) n/=pri[j];

        fac.PB(pri[j]);

    }

    if(n>1) fac.PB(n);

    int m=fac.size();

    ll ans=0;

    for(int i=0;i<(1<<m);++i) {

        ll d=1; int mu=1;

        for(int j=0;j<m;++j) if(i>>j&1)

            d*=fac[j],mu=-mu;

        ans+=mu*(R/d-L/d);

    }

    fac.clear();

    return ans;

}



int main() {

    getpri(100000);

    int T; rd(T);

    while(T--) {

        ll a,m; rd(a),rd(m);

        ll d=gcd(a,m);

        printf("%lld\n",cal((a-1)/d,(a+m-1)/d,m/d));

    }

    return 0;

}


Comments

Submit
0 Comments
More Questions

1327B - Princesses and Princes
1450F - The Struggling Contestant
1399B - Gifts Fixing
1138A - Sushi for Two
982C - Cut 'em all
931A - Friends Meeting
1594A - Consecutive Sum Riddle
1466A - Bovine Dilemma
454A - Little Pony and Crystal Mine
2A - Winner
1622B - Berland Music
1139B - Chocolates
1371A - Magical Sticks
1253A - Single Push
706B - Interesting drink
1265A - Beautiful String
214A - System of Equations
287A - IQ Test
1108A - Two distinct points
1064A - Make a triangle
1245C - Constanze's Machine
1005A - Tanya and Stairways
1663F - In Every Generation
1108B - Divisors of Two Integers
1175A - From Hero to Zero
1141A - Game 23
1401B - Ternary Sequence
598A - Tricky Sum
519A - A and B and Chess
725B - Food on the Plane