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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章