题解:P16065 [CSPro 32] 因子化简

· · 题解

题目传送门:P16065 [CSPro 32] 因子化简 题解

题目分析

题意概括

多组询问,每次给出 n 和 k,对 n 做质因数分解,求所有质因子中次数大于 k 的质因子的全部幂次的乘积,若没有则返回1。

注意

数据范围:1\le q \le 3\times10^5,1\le n \le 3\times10^5,1\le k \le 10^9, 则必须用long long,否则质因子的高次幂会超出int范围;

算法思路

  1. 质因数分解:对每个 n 做质因数分解。
  2. 筛选质因子:排除比 k 小的质因子指数。
  3. 处理剩余质因子:分解结束后,若 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; }