题目:https://codeforces.com/contest/1152/problem/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?
Input
The only line contains two integers aa and bb (1≤a,b≤1091≤a,b≤109).
Output
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.
Examples
input
Copy
6 10
output
Copy
2
input
Copy
21 31
output
Copy
9
input
Copy
5 10
output
Copy
0
大意:求当(a+k)与(b+k)的lcm最小时,k的值
若对统一lcm有多个k,输出k的最小值。
思路:
因此我们暴力枚举b-a的因子(实际上是暴力枚举a+k与b-a的最大公因数),比较lcm的值同时记录lcm、k即可
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll fac[200005];
int main()
{
ll n,m,i,j,k,ans,num,sum,a,b,c,tot,lcm;
scanf("%lld%lld",&a,&b);
if(a>b) swap(a,b);
c=b-a,tot=0;
for(i=1;i<=sqrt(c);i++) //因子
if(c%i==0) fac[tot++]=i,fac[tot++]=c/i;
if(!tot)
{
printf("0\n");
return 0;
}
ans=0x3f3f3f3f3f3f3f3f;
for(i=0;i<tot;i++)
{
num=(a%fac[i]==0?0:(a/fac[i]+1)*fac[i]-a);
lcm=(a+num)*(b+num)/fac[i];
if(lcm<ans) k=num,ans=lcm;
else if(lcm==ans&&num<k) k=num;
}
printf("%lld\n",k);
return 0;
}