牛客小白月赛71E题题解

猫猫与数学

在这里插入图片描述

问题建模

给定两个正整数a,b,问能否找到最小的整数c,使得gcd(a+c,b+c)不等于1,若可以输出c,不行则输出-1。

问题分析

1.转换条件

将a,b变为a>=b的形式,然后采用更相减损法将gcd(a+c,b+c)变为gcd(a-b,b+c),这样新的gcd()里面就只有一个未知数。

2.分析新的gcd

由于a-b为定值,则gcd求出的公约数可以通过a-b的约数找到,在找到一个约数后判断是否能构造出一个有同样约数b+c即可,最终输出最小的c即可。

3.方法1筛约数判断

代码
#include<bits/stdc++.h>

#define x first
#define y second
#define C(i) str[0][i]!=str[1][i]
using namespace std;
typedef unsigned long long ULL;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
const int N = 2e5 + 10, P = 2048;
const LL INF=1e18;
LL a,b;
LL check(LL x){
    if(x==1)    return INF;
    ///不需要考虑b%x==0的情况,因为该情况在判断gcd(a,b)>1时已经判断了
    return  x-b%x; 
}

void solve() {
    cin >>a >>b;
    if(a<b) swap(a,b);
    if(__gcd(a,b)>1)    puts("0");
    else{
        ///特判,差1时,公约数只能为1,故输出-1。相等且不为偶数时,+1至少有公因子2,>1
        if(a-b==1)  puts("-1");
        else if(a-b==0) puts("1");
        else {
            LL s=a-b;
            LL res=INF;
            for(LL i=1;i<=s/i;i++){
                if(s%i==0){
                    res=min({res,check(i),check(s/i)});
                }
            }
            cout <<res <<"\n";
        }
    }
}


int main() {
    int t = 1;
    //cin >> t;
    while (t--) solve();
    return 0;
}

4.方法2筛质因子判断

代码
#include<bits/stdc++.h>

#define x first
#define y second
#define C(i) str[0][i]!=str[1][i]
using namespace std;
typedef unsigned long long ULL;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
const int N = 2e5 + 10, P = 2048;
const LL INF=1e18;

void solve() {
    LL a,b;
    cin >>a >>b;
    if(a<b) swap(a,b);
    if(__gcd(a,b)>1)    puts("0");
    else{
        if(a-b==1)  puts("-1");
        else if(a-b==0) puts("1");
        else {
            LL s=a-b;
            LL res=INF;
            for(LL i=2;i<=s/i;i++){
                if(s%i==0){
                    res=min(res,i-b%i);
                    while(s%i==0)   s/=i;
                }
            }
            if(s>0) res=min(res,s-b%s);
            cout <<res <<"\n";
        }
    }
}


int main() {
    int t = 1;
    //cin >> t;
    while (t--) solve();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值