Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.
Neko has two integers a and b. His goal is to find a non-negative integer k such that the least common multiple of a+k and b+k is the smallest possible. If there are multiple optimal integers k, 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 a and b (1≤a,b≤109).
Output
Print the smallest non-negative integer k (k≥0) such that the lowest common multiple of a+k and b+k is the smallest possible.
If there are many possible integers k giving the same value of the least common multiple, print the smallest one.
Examples
Input
6 10
Output
2
Input
21 31
Output
9
Input
5 10
Output
0
题意:给出两个整数a,b,寻找一个最小的非负整数k使得Lcm(a+k,b+k)尽可能的小。
解析:gcd具有这样的性质 〖 gcd〗(a,b)=gcd(a,b-a)(a<b)
L c m ( a + k , b + k ) = ( a + k ) ( b + k ) / g c d ( a + k , b + k ) = ( ( a + k ) ( b + k ) ) / ( g c d ( a + k , b + k − a − k ) ) = ( ( a + k ) ( b + k ) ) / ( g c d ( a + k , b − a ) ) Lcm(a+k,b+k)=(a+k)(b+k)/gcd(a+k,b+k) =((a+k)(b+k))/(gcd(a+k,b+k-a-k))=((a+k)(b+k))/(gcd(a+k,b-a)) Lcm(a+k,b+k)=(a+k)(b+k)/gcd(a+k,b+k)=((a+k)(b+k))/(gcd(a+k,b+k−a−k))=((a+k)(b+k))/(gcd(a+k,b−a))
gcd(a+k, b-a)的结果一定是(b-a)的因子,所以可以枚举因子来求最小的lcm
首先枚举b-a的因子,用vector
再求k;q一定也是a+k的因子;(a+k)%q==0;
当前q一定,gcd == q;要使lcm最小,分子的k就要尽量小;
当a<=q时,可使k==q-a;
当a>q时,因为(a+k)%q==0;所以(a%q+k%q)%q==0;
使k最小,所以令a%q+k%q==q;k<q;k%q==k;
所以k=q-a%q;
然后枚举lcm,就是答案
#include <iostream>
#include <cmath>
#include<queue>
#include <map>
#include <stdio.h>
#include<cstring>
#include <algorithm>
#include<cstdlib>
#include<vector>
using namespace std;
typedef long long ll;
const ll inf=1e18;
int gcd(int a, int b)
{return b == 0 ? a : gcd(b, a % b);}
int main()
{
int k[100055];
ll a,b,t=1;
vector<ll> q;
cin>>a>>b;
if(a>b)swap(a,b);
if(b%a==0)
{
cout<<0<<endl;return 0;
}
for(ll i=1;i*i<b-a;i++)
if((b-a)%i==0)
q.push_back(i),q.push_back((b-a)/i);
int n=q.size();
k[0]=0;
for(int i=0;i<n;i++)
{
if(a<=q[i])
k[t++]=q[i]-a;
else
k[t++]=q[i]-a%q[i];
}
ll lcm=inf,ans=0;
for(int i=0;i<t;i++)
{
ll tem=(a+k[i])/gcd(a+k[i],b-a)*(b+k[i]);
if(lcm>tem)
lcm=tem,ans=k[i];
}
cout<<ans<<endl;
}