一个正整数N的因子中可能存在若干连续的数字。例如630可以分解为3*5*6*7,其中5、6、7就是3个连续的数字。给定任一正整数N,要求编写程序求出最长连续因子的个数,并输出最小的连续因子序列。
输入格式:
输入在一行中给出一个正整数N(1< N< 231)。
输出格式:
首先在第1行输出最长连续因子的个数;然后在第2行中按“因子1*因子2*……*因子k”的格式输出最小的连续因子序列,其中因子按递增顺序输出,1不算在内。
输入样例:
630
输出样例:
3
5*6*7
题意:求最长连续因子的个数及该个数下最小的连续因子序列(一开始我直接求成了最小连续因子序列,被坑了)。
思路:需要点数学思维,直接用暴力求解
注意两点:1、由于题目要求输出最小的连续因子序列,故起点从小开始枚举,相同个数下保存较小的序列即可;
2、输入的数n可能是质数,这样我们可能找不到连续因子,故在最后要判断一下若是质数直接输出1和n
代码:
#include<iostream>
#include<map>
#include<vector>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
int main()
{
int n,x;
while(cin>>n){
int maxn=sqrt(n),t=0;
for(int i=2; i<=maxn; i++){//枚举起点
int temp=n,tot=0,j=i;
while(!(temp%j)){
temp/=j;
tot++;
j++;
}
if(tot>t){//更新最长因子个数
t=tot;
x=j-1;//记录最大的因子
}
}
if(t){
cout<<t<<endl;
for(int i=x-t+1; i<x; i++) cout<<i<<"*";
cout<<x<<endl;
}
else printf("1\n%d\n",n);//如果是质数,直接输出1和n
}
return 0;
}