一个正整数 ( N ) 的因子中可能存在若干连续的数字。例如 630 可以分解为 ( 3 \times 5 \times 6 \times 7 ),其中 5、6、7 就是 3 个连续的数字。给定任一正整数 ( N ),要求编写程序求出最长连续因子的个数,并输出最小的连续因子序列。
输入格式:
输入在一行中给出一个正整数 ( N )(( 1 < N < 2^{31} ))。
输出格式:
首先在第 1 行输出最长连续因子的个数;然后在第 2 行中按 因子1*因子2*……*因子k
的格式输出最小的连续因子序列,其中因子按递增顺序输出,1 不算在内。
输入样例:
630
输出样例:
3
5*6*7
限制条件:
- 代码大小限制: 16 KB
- 时间限制: 400 ms
- 内存限制: 64 MB
- 栈大小限制: 8192 KB
代码
#include <bits/stdc++.h>
using namespace std;
#define int long long
// 函数用于找出给定数n的所有因子
vector<int> findFactors(int n) {
vector<int> factors;
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
factors.push_back(i);
if (i != n / i) {
factors.push_back(n / i);
}
}
}
if (n > 1) {
factors.push_back(n);
}
sort(factors.begin(), factors.end());
return factors;
}
void solve() {
int n;
cin >> n;
if (n == 1) {
cout << 1 << endl << 1;
return;
}
vector<int> factors = findFactors(n);
int maxConsecutiveCount = 0;
vector<int> maxConsecutiveFactors;
for (int i = 0; i < factors.size(); ++i) {
int t = n;
int currentCount = 1;
vector<int> currentFactors;
currentFactors.push_back(factors[i]);
t /= factors[i];
for (int j = i + 1; j < factors.size(); ++j) {
if (factors[j] - factors[j - 1] == 1&&t%factors[j]==0) {
t /= factors[j];
currentCount++;
currentFactors.push_back(factors[j]);
}
else {
break;
}
}
if (currentCount > maxConsecutiveCount) {
maxConsecutiveCount = currentCount;
maxConsecutiveFactors = currentFactors;
}
}
cout << maxConsecutiveCount << endl;
for (int i = 0; i < maxConsecutiveFactors.size(); ++i) {
if (i > 0) {
cout << "*";
}
cout << maxConsecutiveFactors[i];
}
cout << endl;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
solve();
return 0;
}