cf Educational Codeforces Round 26 E. Vasya's Function

原题:
E. Vasya’s Function
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Vasya is studying number theory. He has denoted a function f(a, b) such that:

f(a, 0) = 0;
f(a, b) = 1 + f(a, b - gcd(a, b)), where gcd(a, b) is the greatest common divisor of a and b.
Vasya has two numbers x and y, and he wants to calculate f(x, y). He tried to do it by himself, but found out that calculating this function the way he wants to do that might take very long time. So he decided to ask you to implement a program that will calculate this function swiftly.

Input
The first line contains two integer numbers x and y (1 ≤ x, y ≤ 1012).

Output
Print f(x, y).

Examples
input
3 5
output
3
input
6 3
output
1

中文:
f(a, 0) = 0;
f(a, b) = 1 + f(a, b - gcd(a, b))

问你上面公式得到最后结果要计算多少步?

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll gcd(ll x,ll y)
{
    return y==0?x:gcd(y,x%y);
}
ll x,y;
vector<ll> factor_x;

int main()
{
    ios::sync_with_stdio(false);
    ll x,y;
    while(cin>>x>>y)
    {
        factor_x.clear();
        ll tmp=x;
        for(ll i=2;i*i<=x;i++)
        {
            if(tmp%i==0)
            {
                factor_x.push_back(i);
                while(tmp%i==0)
                    tmp/=i;
            }
        }
        if(tmp>1)
            factor_x.push_back(tmp);

        ll ans=0,g;
        while(y)
        {
            g=gcd(x,y);
            x/=g;
            y/=g;
            tmp=y;
            for(auto i:factor_x)
            {
                if(x%i==0)
                    tmp=min(tmp,y%i);
            }
            ans+=tmp;
            y-=tmp;

        }
        cout<<ans<<endl;
    }
    return 0;
}

解答:

公式当中,输入的a是不变的,而b的变化相当于

bi=bi1gcd(a,bi1)

所以,只需要考虑b的变化即可

例如输入a和b为420 779

那么,如果暴力的计算过程应该是

括号中的数代表前面的数减去括号中的数得到下一个数。

779-(1)->778-(2)->776-(4)->772-(4)->768-(12)->756-(84)->672-(84)->588-(84)->504-(84)->420

可见,每次b减去的数分别为1,2,4,12,84

那么,b每次减去多少个上一次的最大公约数,会得到一个新的最大公约数?

参考此博客

a=gcd(a,b)×A, b=gcd(a,b)×B,b减去1次最大公约数的结果是a=gcd(a,b)×A, b=gcd(a,b)×(B-1)

现在设减去k次以后a和b的最大公约数发生变化

a=gcd(a,b)×A, b=gcd(a,b)×(B-k)

gcd(a,b)=gcd(gcd(a,b)×A ,gcd(a,b)×(B-k))

右侧提出gcd(a,b)有

gcd(a,b)×gcd(A ,(B-k))

此时gcd(A ,(B-k)) 不等于1

如何计算k?

设r为A的一个因子,有(B-k)%r=0,变形有B=q*r+k,B%r=k%r,相当于k是B取模r的结果,所以k一定小于r,最后得到B%r=k这个结论,得到了k的算法

此时计算出a的所有质因子即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值