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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhao5502169/article/details/89528454

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;
}

猜你喜欢

转载自blog.csdn.net/zhao5502169/article/details/89528454
今日推荐