https://codeforces.com/problemset/problem/1152/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 \le a, b \le 10^91≤a,b≤109 ).
输出格式
Print the smallest non-negative integer kk ( k \ge 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.
题意翻译
给定两个正整数a,ba,b,找到非负整数kk使a+ka+k与b+kb+k的最小公倍数最小,如有多解输出最小的kk
输入输出样例
输入 #1复制
6 10
输出 #1复制
2
输入 #2复制
21 31
输出 #2复制
9
输入 #3复制
5 10
输出 #3复制
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.
开始想暴力猜,猜一手三分的模型直接gg。
那就数学推导:
假设a<=b
首先lcm的公式:lcm(a + k,b + k) = (a + k) * (b + k) / gcd(a + k,b + k)
然后已知有辗转相除法和辗转相减法。这里用辗转相减gcd(a,b)=gcd(b,a-b)进行转化
原式子gcd(a+k,b+k)==gcd(a+k,b-a)。
b-a是个常数,所以gcd(a+k,b-a)==p,这个p出自b-a的因子,通过枚举这个因子去求k。
首先意识到(a+k)%p==0。然后这个式子分母的值是p,分子的值和k的大小有关,想要使结果lcm小,那么每次取最小的满足的k。
最小的满足的k是多少呢? (a+k)%p==0 ----(a%p+k%p)%p==0------(a%p+k)==p------k=p-a%p;
然后在所有的因子p中取达到lcm最小的k作为答案。
当然如果开始b%a==0的话,那么直接就是k=0最小的了并且lcm(a,b)也是最小的,不管怎么加都会至少lcm(a,b)>=b
这题的启发:gcd(a+k,b+k)可以用辗转相减法进行化简
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5;
typedef long long LL;
vector<LL>v;
int main(void)
{
cin.tie(0);std::ios::sync_with_stdio(false);
LL a,b;cin>>a>>b;
if(a>b) swap(a,b);
if(b%a==0)
{
cout<<0<<endl;return 0;
}
LL lcm1=a/__gcd(a,b)*b;
for(LL i=1;i<=sqrt(b-a);i++){
if((b-a)%i==0) v.push_back(i),v.push_back((b-a)/i);
}
LL k=0;
for(LL i=0;i<v.size();i++)
{
LL u=v[i];
LL f=u-a%u;
if((a+f)*(b+f)/u<lcm1)
{
lcm1=(a+f)*(b+f)/u;
k=f;
}
}
cout<<k<<endl;
return 0;
}