description:
输入一个数a和b 求他们所有的公约数 a,b范围为1e13
solution:
数据范围大 直接暴力肯定是不行的 先gcd求他们的最大公约数x 那么有 a%x = 0 , b % x = 0 题目要求所有约数 设x的任意因子为i 那么有x%i = 0 , 所以有 a % i = 0 , b % i = 0,那么我们枚举出所有x的因子即可 注意去重 可以用vector存一下 gcd 复杂度是log的
枚举因子为 sqrt(n) 可通过此题 注意因子的大小可能超过int vector使用LL类型
code:
#include <bits/stdc++.h> using namespace std; #define LL long long #define ULL unsigned long long #define mes(x, a) memset(x, a, sizeof(x)); #define sca(a) scanf("%d", &a) #define lowbit(x) x &(-x) #define mk make_pair #define pb(x) push_back(x) #define all(x) (x).begin(), (x).end() #define fi first #define se second #define lson v << 1 #define rson v << 1 | 1 #define pii pair<int, int> inline void read(int &x) { x = 0; int flag_read = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') flag_read = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = (x << 3) + (x << 1) + c - '0'; c = getchar(); } x *= flag_read; } void out(int x) { if (x > 9) { out(x / 10); } putchar(x % 10 + '0'); } vector<LL> v; int main() { ios::sync_with_stdio(0); LL a, b; cin >> a >> b; LL x = __gcd(a, b); for (LL i = 1; i * i <= x; i++) { if (x % i == 0) { v.pb(i); if (i != x / i) v.pb(x / i); } } sort(all(v)); for(int i = 0;i < v.size();i ++){ cout << v[i] << ' '; } cout << '\n'; return 0; }