給定 n 個正整數,求它們乘積的**最小因子**,該因子擁有**超過 2 個因子**(含 1 和自身)。即:找最小的**非質數且非質數平方**的因子。若不存在輸出 -1。
a[i] 質因子分解,**只保留最小的兩個質因子**(含重複,如 8=2×2×2 保留 2,2)。b[],排序。b.size < 2 輸出 -1;否則輸出 b[0] * b[1](已保證為最小合格因子)。#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define LL long long
using namespace std;
LL a[111], b[111111];
int main() {
int T; cin >> T;
while (T--) {
int n; cin >> n;
int cnt = 0;
for (int i = 1; i <= n; i++) {
scanf("%lld", &a[i]);
LL x = a[i];
int got = 0;
for (LL p = 2; p * p <= x && got < 2; p++) {
while (x % p == 0 && got < 2) {
b[++cnt] = p;
x /= p;
got++;
}
}
if (x > 1 && got < 2) { // 剩下一個大質因子
b[++cnt] = x;
got++;
}
}
if (cnt < 2) cout << -1 << '\n';
else {
sort(b + 1, b + cnt + 1);
cout << b[1] * b[2] << '\n';
}
}
return 0;
}
p * p <= x 動態縮小上界,避免 TLE。got < 2 控制每個數最多貢獻兩個因子。long long,乘積可能超 32 位。本題核心在於**「因子個數 > 2」等價於「非質數」**,並利用「最小質因子組合」構造答案,避開大數乘積陷阱。