题目信息
1096. Consecutive Factors (20)
时间限制400 ms
内存限制65536 kB
代码长度限制16000 B
Among all the factors of a positive integer N, there may exist several consecutive numbers. For example, 630 can be factored as 3*5*6*7, where 5, 6, and 7 are the three consecutive numbers. Now given any positive N, you are supposed to find the maximum number of consecutive factors, and list the smallest sequence of the consecutive factors.
Input Specification:
Each input file contains one test case, which gives the integer N (1
解题思路
分奇偶两种情况讨论
AC代码
#include <algorithm>
#include<set>
#include<queue>
#include<map>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
using namespace std;
void dfsFactor(long long n, long long preNum, vector<int>&factor, vector<vector<int>>&ans,int&factorSize)
{
if (n % (preNum + 1) == 0)
{
factor.push_back(preNum + 1);
dfsFactor(n / (preNum + 1), preNum + 1, factor, ans, factorSize);
}
else if (!factor.empty() && factor.size() > factorSize)
{
factorSize = factor.size();
ans.push_back(factor);
}
}
bool cmp(const vector<int>&a, const vector<int>&b)
{
if (a.size() > b.size())
return true;
else if (a.size() == b.size() && a[0] < b[0])
return true;
else return false;
}
int main(void)
{
int n;
cin >> n;
if (n % 2 == 1)
{
int temp = (int)((double)sqrt(n) + 1);
for (int i = 2; i <= temp; ++i)
{
if (n%i == 0)
{
cout << "1" << endl;
cout << i << endl;
return 0;
}
}
cout << "1" << endl;
cout << n << endl;
}
else
{
vector<int> maxFactor = { INT_MAX, n, (int)((double)sqrt(n) + 1), 1290, 215, 73, 35, 21, 14, 10, 0 };//3~13
vector<int> factor(0);
vector<vector<int>>ans(0);
int factorSize = 0;
for (long long i = 1; i <= min(n, maxFactor[factorSize + 1]); i++)
{
if (n % (i + 1) == 0)
{
dfsFactor(n, i, factor, ans, factorSize);
factor.clear();
}
}
sort(ans.begin(), ans.end(), cmp);
cout << ans[0].size() << endl;
for (int i = 0; i < ans[0].size(); i++)
{
cout << ans[0][i];
if (i != ans[0].size() - 1)
cout << "*";
}
cout << endl;
}
return 0;
}

本文介绍了一种算法,用于找出正整数N的最大连续因子序列,并列出这些连续因子。通过递归深度优先搜索的方法来查找所有可能的连续因子组合,并选择最长序列。
187

被折叠的 条评论
为什么被折叠?



