题解:P16065 [CSPro 32] 因子化简
realize_dreams · · 题解
题目传送门:P16065 [CSPro 32] 因子化简 题解
题目分析
题意概括
多组询问,每次给出
注意
数据范围:
算法思路
- 质因数分解:对每个
n 做质因数分解。 - 筛选质因子:排除比
k 小的质因子指数。 - 处理剩余质因子:分解结束后,若
n>1 ,说明剩余一个大于\sqrt{n} 的质因子,其次数为1,若k\le1 则将其乘入答案;代码实现
#include<bits/stdc++.h> #define int long long // 防止数据溢出 using namespace std;
// 快速读入,避免cin超时 inline int read() { int f = 1, x = 0; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = x 10 + ch - '0'; ch = getchar(); } return x f; }
// 快出 inline void out(int x) { if (x < 0) putchar('-'), x = -x; if (x > 9) out(x / 10); putchar(x % 10 + '0'); }
const int N = 3e5 + 5; // 依照数据范围
// 计算单个n和k的答案 int solve(int n, int k) { int res = 1; for (int i = 2; i i <= n; ++i) { // 质因数分解 if (n % i == 0) { int cnt = 0; while (n % i == 0) { cnt++; n /= i; } if (cnt >= k) { // 筛选次数≥k的质因子 int p = 1; for (int j = 0; j < cnt; ++j) p = i; res = p; } } } if (n > 1) { // 处理剩余的质因子 if (1 >= k) res = n; } return res; }
int32_t main() { int q = read(); while (q--) { int n = read(), k = read(); int ans = solve(n, k); out(ans); putchar('\n'); // 换行 } return 0; }