洛谷 P1072 Hankson的趣味题【GCD | LCM】

题目链接

题目描述:

给出四个正整数 a 0 , a 1 , b 0 , b 1 a_0,a_1,b_0,b_1 a0,a1,b0,b1,设某正整数 x 满足:

  1. g c d ( x , a 0 ) = a 1 gcd(x,a_0)=a_1 gcd(x,a0)=a1
  2. l c m ( x , b 0 ) = b 1 lcm(x,b_0)=b_1 lcm(x,b0)=b1

输出满足条件的 x 的个数
其中 1 ≤ a 0 , a 1 , b 0 , b 1 ≤ 2 ∗ 1 0 9 1≤a_0,a_1,b_0,b_1≤2*10^9 1a0,a1,b0,b12109 且 n ≤ 2000。


题解:

朴素想法:
  1. g c d ( x , a 0 ) = a 1 gcd(x,a_0)=a_1 gcd(x,a0)=a1 我们可知, a 1 a_1 a1 是 x 的因子。
  2. l c m ( x , b 0 ) = b 1 lcm(x,b_0)=b_1 lcm(x,b0)=b1 我们可知,x 是 b 1 b_1 b1 的因子。
  3. 所以我们想到用试除法求出 b 1 b_1 b1 所有的约数 x,逐一判断 x 是否满足这两个条件。
  4. 但这样有一个点会超时,所以我们对 gcd 和 lcm 的过程进行如下优化:
gcd:

g c d ( x , a 0 ) = a 1 gcd(x,a_0)=a_1 gcd(x,a0)=a1
—> g c d ( x / a 1 , a 0 / a 1 ) = 1 gcd(x/a_1,a_0/a_1)=1 gcd(x/a1,a0/a1)=1

lcm:

l c m ( x , b 0 ) = b 1 lcm(x,b_0)=b_1 lcm(x,b0)=b1
—> x ∗ b 0 / g c d ( x , b 0 ) = b 1 x*b_0/gcd(x,b_0)=b_1 xb0/gcd(x,b0)=b1
—> g c d ( x , b 0 ) = x ∗ b 0 / b 1 gcd(x,b_0)=x*b_0/b_1 gcd(x,b0)=xb0/b1
—> g c d ( b 1 / b 0 , b 1 / x ) = 1 gcd(b_1/b_0,b_1/x)=1 gcd(b1/b0,b1/x)=1

这样就优化了gcd 和 lcm ,就成功通过最后一个点啦


AC code:

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <deque>
#include <list>
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
//#pragma GCC optimize(2)
using namespace std;
typedef long long ll;
//cout << fixed << setprecision(2);
//cout << setw(2);
const int N = 2e5 + 6, M = 1e9 + 7;

int gcd(int a, int b) {
    return b ? gcd(b, a % b) : a;
}

int main() {
    //freopen("/Users/xumingfei/Desktop/ACM/test.txt", "r", stdin);
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    int T;
    cin >> T;
    while (T--) {
        int a, b, c, d, ans = 0;
        cin >> a >> b >> c >> d;
        for (int i = 1; i * i <= d; i++) {
            if (d % i == 0) {
                if (i % b == 0 && gcd(a / b, i / b) == 1 && gcd(d / c, d / i) == 1) ans++;
                int j = d / i;
                if (j == i) continue;
                if (j % b == 0 && gcd(a / b, j / b) == 1 && gcd(d / c, d / j) == 1) ans++;
            }
        }
        cout << ans << '\n';
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值