codeforces 837E

来源:互联网 发布:ubuntu传文件 编辑:程序博客网 时间:2024/06/07 08:12

题解

首先我们知道

gcd(a,b)=gcd(a,a+b)f(a,b)=f(a,bgcd(a,b))

b=ka+m
gcd(a,b)=gcd(a,m)

f(a,b)=f(a,ka+mgcd(a,m))=k+f(a,mgcd(a,m))=k+f(a,m)

f(a,b)=b/a+f(a,bmoda)


设gcd(a, b) = d
f(a,b)=f(a/d,b/d)


若a为质数, b < a
f(a,b)=b

那么我们可以递归求解
a不为质数且a,b互质时我们找最接近b且和a不互质的数字就可
每次递归会约去一个质因子,1e12最多十几次…

code:

#include <bits/stdc++.h>using namespace std;typedef long long ll;namespace IO{    inline ll read()    {        ll x=0,f=1;        char ch=getchar();        while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}        while(ch>='0'&&ch<='9'){x=10*x+ch-'0';ch=getchar();}        return x*f;    }}namespace Number_Theory{    ll fac[15];    int len;    bool isPrime[1000010];    ll p[1000001 / 5];    int k;    void init()    {        memset(isPrime, true, sizeof isPrime);        for(int i = 2; i < 1000001; ++i)        {            if(isPrime[i])p[++k] = i;            for(int j = 1; j <= k && i * p[j] < 1000001; ++j)            {                isPrime[i * p[j]] = 0;                if(i % p[j] == 0) break;            }        }    }    void div(ll n)    {        memset(fac, 0, sizeof fac);        len = 0;        for(int i = 1; p[i] * p[i] <= n && i <= k; ++i)        {            if(n % p[i] == 0)            {                fac[++len] = p[i];                while(n % p[i] == 0) n /= p[i];            }        }        if(n > 1) fac[++len] = n;    }    ll Get(ll x)    {        ll pos = 0;        int id = -1;        for(int i = 1; i <= len; ++i)        {            ll tmp = x / fac[i] * fac[i];            if(tmp >= pos)            {                pos = tmp;                id = i;            }        }        return pos;    }    ll gcd(ll a, ll b){return b == 0 ? a : gcd(b, a % b);}    bool judge(ll x)    {        if(x < 1000001) return isPrime[x];        for(int i = 1; i <= k && p[i] * p[i] <= x; ++i)        {            if(x % p[i] == 0) return false;        }        return true;    }    ll solve(ll x, ll y)    {        if(judge(x)) return y;       // ll d;        div(x);        ll pos = Get(y);        ll d = gcd(x, pos);        return y - pos + solve(x / d, pos / d);    }}int main(){    Number_Theory::init();    ll x, y;    x = IO::read(), y = IO::read();    ll ans = 0;    ans += y / x;    y %= x;    Number_Theory::div(x);    printf("%I64d\n", ans + (y == 0 ? 0 : Number_Theory::solve(x, y)));    return 0;}
原创粉丝点击