您的位置:首页 > 其它

cf Educational Codeforces Round 26 E. Vasya's Function

2017-08-12 11:30 375 查看
原题:

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=bi−1−gcd(a,bi−1)

所以,只需要考虑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的所有质因子即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: