Neko does Maths CodeForces - 1152C

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

6 10

Output

2

Input

21 31

Output

9

Input

5 10

Output

0

Note

In the first test, one should choose k=2k=2, as the least common multiple of 6+26+2and 10+210+2 is 2424, which is the smallest least common multiple possible.

题意:给你一个a,给你一个b,让你求一个k,使得lcm(a+k,b+k)最小。

思路:

当a>b时:

关键:gcd(a,b)==gcd(b,a-b)   a>b  //更相减损法求gcd

枚举a-b的因子x,如果x是b的因子,那么k一定=0,否则最小的k=(b/x+1)*x-b;

#include<cmath>
#include<vector>
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
using namespace std;
vector<ll> v;
int main()
{
	ll a,b;
	scanf("%lld%lld",&a,&b);
	if(a==b)
	{
		printf("0\n");
		return 0;
	}
	if(a<b) swap(a,b);//a>b 
	ll maxx=a-b;
	ll ans=a/(__gcd(a,b))*b;
	for(int i=1;i*i<=maxx;i++)
	{
		if(maxx%i==0)
		{
			v.push_back(i);
			v.push_back(maxx/i);
		}
	}
	ll k,lcm,pos=0;
	for(int i=0;i<v.size();i++)
	{
		if(b%v[i]==0) k=0;
		else k=((b/v[i]+1)*v[i]-b);
		ll lcm=(a+k)*(b+k)/v[i];
		if(lcm<ans)
		{
			ans=lcm;
			pos=k;
		}
		else if(lcm==ans&&k<pos)
		{
			pos=k;
		}
	}
	printf("%lld\n",pos);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/why932346109/article/details/89577719