没有细细去分析题目,方法有点繁琐,而且还有一个1分的测试点超时。。。
有的地方有些问题,因式有重复的情况,不过对于结果来说不影响
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> all_factors,out_factors,temp_factors,fin_factors;
int n;
bool IsFactors(vector<int> &it){
int prod=1;
for(int i=0;i<it.size();i++){
prod*=it[i];
}
if(prod==n) return true;
else
return false;
}
bool GetAllFactors(int begin){//把n分解为若干个大于begin的因子的乘积形式
int temp=n;
for(int i=begin;i*i<=n;i++){
if(temp%i==0&&temp!=0){//temp!=0为了防止当上一次循环时temp<i导致temp/=i之后temp=0
all_factors.push_back(i);
temp/=i;
}
}
//if(temp!=1)
all_factors.push_back(temp);//有重复的情况
if(IsFactors(all_factors)){
return true;
}
else{
return false;
}
}
int LongestFactors(vector<int> &it){
int count=1,maxcount=0;
temp_factors.clear();
temp_factors.push_back(it[0]);
for(int i=1;i<it.size();i++){
if(it[i]==it[i-1]+1){
temp_factors.push_back(it[i]);
count++;
}
else{
if(maxcount<count){
maxcount=count;
out_factors.clear();
out_factors=temp_factors;
}
temp_factors.clear();
temp_factors.push_back(it[i]);
count=1;
}
}
if(maxcount<count){//只有一个因子
maxcount=count;
out_factors.clear();
out_factors=temp_factors;
}
return maxcount;
}
int main(){
cin>>n;
if(n==2|| n==3){//因为下面i从2开始,且i*i<=n,所以2、3单独讨论
printf("1\n%d",n);
return 0;
}
int maxcount=0,count=1;//因为当只有一个因子时,70行的判断条件maxcount<count能进入,所以maxcount=0,count随意
for(int i=2;i*i<=n;i++){
all_factors.clear();//每一轮循环找出若干个乘积等于n的大于i的因子,暂存于all_factors
if(GetAllFactors(i)){
count=LongestFactors(all_factors);
if(maxcount<count){
maxcount=count;
fin_factors.clear();
fin_factors=out_factors;
}
}
}
cout<<maxcount<<endl;
for(int i=0;i<fin_factors.size();i++){
if(i!=0) printf("*");
printf("%d",fin_factors[i]);
}
return 0;
}
题解上的答案,思路比较直接点,简单又好懂
代码贴下
#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long LL;
int main(){
LL n;
cin>>n;
LL sqr = (LL)sqrt(1.0*n);
LL ansI = 0;//第一个整数
LL ansLen = 0;//最长连续整数的长度
for(LL i = 2; i <= sqr; i++){
LL temp = 1, j = i;//temp为当前连续整数的乘积
while(1){
temp *= j;
if(n % temp != 0) break;
if(ansLen < j-i+1){
ansLen = j-i+1;
ansI = i;
}
j++;
}
}
if(ansLen == 0){
printf("1\n%lld",n);
}
else{
cout<<ansLen<<endl;
for(LL i = 0; i < ansLen; i++){
if(i!=0) printf("*");
printf("%lld",ansI++);
}
}
return 0;
}