codeforces#1152C. Neko does Maths(最小公倍数)
题目链接:
http://codeforces.com/contest/1152/problem/C
题意:
给出两个数$a$和$b$
找一个$k(k\geq 0)$得到最小的$LCM(a+k,b+k)$
如果有多个$k$,输出最小的$k$
数据范围:
$1 \le a, b \le 10^9$
分析:
假设 $gcd\left ( a+k,b+k\right )= t$
那么$(a+k)\%t=(b+k)\%t=0$
化简得到$a\%t=b\%t$
$a-x\times t=b-y\times t$($x,y$为任意整数)
化简得到$\frac{a-b}{y-x}=t$
所以$t$一定是$a-b$的因数
然后枚举所有$t$,找到最小的$LCM$
ac代码:
#include<bits/stdc++.h>
#define ll long long
#define pa pair<int,int>
#define mak make_pair
using namespace std;
const int maxn=1e6+10;
const int maxm=1e7+10;
const ll INF=1e18;
ll ans,a,b;
int ansk=0;
void cal(int i)
{
int k=i-a%i;
k%=i;
if((a+k)*(b+k)/i<ans)
{
ans=(a+k)*(b+k)/i;
ansk=k;
}
}
int main()
{
scanf("%lld %lld",&a,&b);
ans=a*b;
ansk=0;
if(a>b)swap(a,b);
for(int i=1; i*i<=(b-a); i++)
{
if((b-a)%i==0)
{
cal(i);
cal((b-a)/i);
}
}
printf("%d\n",ansk);
return 0;
}

浙公网安备 33010602011771号