[ Codeforces Round #554 (Div. 2) C]
Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.
Neko has two integers aa and bb. His goal is to find a non-negative integer kk such that the least common multiple of a+ka+k and b+kb+k is the smallest possible. If there are multiple optimal integers kk, he needs to choose the smallest one.
Given his mathematical talent, Neko had no trouble getting Wrong Answer on this problem. Can you help him solve it?
The only line contains two integers aa and bb (1≤a,b≤1091≤a,b≤109).
Print the smallest non-negative integer kk (k≥0k≥0) such that the lowest common multiple of a+ka+k and b+kb+k is the smallest possible.
If there are many possible integers kk giving the same value of the least common multiple, print the smallest one.
6 10
2
21 31
9
5 10
0
In the first test, one should choose k=2k=2, as the least common multiple of 6+26+2 and 10+210+2 is 2424, which is the smallest least common multiple possible.
题意:给出两个整数a,b,求出使(a+k)*(b+k)/gcd(a+k,b+k)的值最小的k,如果有多组答案求出最小的k
题解:gcd(a+k,b+k)=gcd(a-b,b+k),所以gcd(a+k,b+k)一定是(a-b)的一个因子,也就是说a+k一定是(a-b)的因子的倍数,即a+k=q*t,所以直接枚举(a-b)的因子q,求出相应的q*t,然后就可以根据k=q*t-a求出k,然后就可以求出最小的(a+k)*(b+k)/gcd(a+k,b+k)了
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 #include<set> 6 #include<map> 7 #include<stack> 8 #include<vector> 9 #include<cmath> 10 #include<algorithm> 11 using namespace std; 12 typedef long long ll; 13 #define debug(x) cout<< #x <<" is "<<x<<endl; 14 int gcd(ll x,ll y){ 15 if(y==0)return x; 16 return gcd(y,x%y); 17 } 18 int main(){ 19 int n,m; 20 scanf("%d%d",&n,&m); 21 if(n<m)swap(n,m); 22 ll xx=n-m; 23 ll ans=-1; 24 ll ans0=0; 25 for(ll i=1;i*i<=xx;i++){ 26 if(xx%i==0){ 27 ll y1=n/i; 28 if(n%i)y1++; 29 y1*=i; 30 y1-=n; 31 if((y1+n)*(y1+m)/gcd(y1+n,y1+m)<ans||ans==-1){ 32 ans=(y1+n)*(y1+m)/gcd(y1+n,y1+m); 33 ans0=y1; 34 } 35 else if((y1+n)*(y1+m)/gcd(y1+n,y1+m)==ans&&y1<ans0){ 36 ans0=y1; 37 } 38 ll y2=n/(xx/i); 39 if(n%(xx/i))y2++; 40 y2*=(xx/i); 41 y2-=n; 42 if((y2+n)*(y2+m)/gcd(y2+n,y2+m)<ans||ans==-1){ 43 ans=(y2+n)*(y2+m)/gcd(y2+n,y2+m); 44 ans0=y2; 45 } 46 else if((y2+n)*(y2+m)/gcd(y2+n,y2+m)==ans&&y2<ans0){ 47 ans0=y2; 48 } 49 } 50 } 51 printf("%lld\n",ans0); 52 return 0; 53 }