CodeForces - 1152C [数学]

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+kak))=((a+k)(b+k))/(gcd(a+k,ba))

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值