Codeforces Round #554 (Div. 2) C. Neko does Maths(数论)

C. Neko does Maths
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
inputCopy
6 10
outputCopy
2
inputCopy
21 31
outputCopy
9
inputCopy
5 10
outputCopy
0
Note
In the first test, one should choose k=2, as the least common multiple of 6+2 and 10+2 is 24, which is the smallest least common multiple possible.

题意:给你两个数a,b,问你lcm(a+k,b+k)最小时k等于多少,如果存在多个k,输出最小的k。

思路:确定目标肯定是gcd(a+k,b+k),假设gcd = gcd(a+k,b+k),则,(a+k)%gcd == 0;(b+k)%gcd == 0;(a+k-b-k) = (a-b)%gcd == 0;
股gcd一定是a-b的一个约数,因为a-b是一个定值,所以枚举他的所有约数,反求出k,以及lcm。维护符合的k即可。

代码如下:

#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
ll a,b;
ll solve(){
    ll diff = abs(a-b);
    ll Mk = diff;
    ll Mlcm = a/__gcd(a,b)*b;
    //最小的LCM和k
    for(ll i=1;i*i<=diff;++i){
        if(diff % i == 0){
            for(ll gcd:{i,diff/i}){
                //求出当前的k
                ll leave = a%gcd;
                ll k = (gcd-leave+gcd)%gcd;
            
                ll lcm = (a+k)/gcd*(b+k);
           //     printf("lcm = %lld,gcd = %lld,nowk = %lld\n",lcm,gcd,nowk);
                if(lcm < Mlcm){
                    Mlcm = lcm;
                    Mk = k;
                }
                else if(lcm == Mlcm && k < Mk){
                    Mk = k;
                }
            }
        }
    }
    return Mk;
}
int main(void){
    scanf("%lld%lld",&a,&b);
    printf("%lld\n",solve());

    return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值