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

本文探讨了如何找到两个整数a和b的最小公倍数的有趣问题,通过选择适当的非负整数k,使得a+k和b+k的最小公倍数尽可能小。文章提供了一种有效的算法实现,首先找出a和b差值的所有因子,然后通过遍历这些因子来确定最优的k值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C. Neko does Maths

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

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

Copy

6 10

output

Copy

2

input

Copy

21 31

output

Copy

9

input

Copy

5 10

output

Copy

0

Note

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.

 

 

分析:众所周知,gcd(a,b)一定是(a-b)的因子,那么直接枚举a-b的因子就可以了。最后判断一下k=0的情况即可。

#include "bits/stdc++.h"

using namespace std;

int main() {
    long long a, b;
    cin >> a >> b;
    long long c = abs(a - b);
    vector<long long> v;
    for (long long i = 1; i * i <= c; ++i) {
        if (c % i == 0) {
            if (i != 1)
                v.push_back(i);
            if (i * i != c)v.push_back(c / i);
        }
    }
    sort(v.begin(), v.end());
    long long mini = 8e18;
    long long ans;
    for (int i = 0; i < v.size(); ++i) {
        long long x = a + v[i] - a % v[i];
        long long y = b + v[i] - b % v[i];
        if (x * y / v[i] < mini) {
            mini = x * y / v[i];
            ans = x - a;
        }
    }
    if (mini >= a * b / __gcd(a, b))ans = 0;
    printf("%lld\n", ans);
}

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值