L1-006 连续因子
一个正整数 N 的因子中可能存在若干连续的数字。例如 630 可以分解为 3×5×6×7,其中 5、6、7 就是 3 个连续的数字。给定任一正整数 N,要求编写程序求出最长连续因子的个数,并输出最小的连续因子序列。
Input
输入在一行中给出一个正整数 N(1<N<231)。
Output
首先在第 1 行输出最长连续因子的个数;然后在第 2 行中按 因子1因子2……*因子k 的格式输出最小的连续因子序列,其中因子按递增顺序输出,1 不算在内。
Examples
输入样例:
630
输出样例:
3
567
题解:
真的是好题, 目前只写成了n^2, 个人感觉一定可以写成n或者nlogn复杂度. 一个数因数的积一定还是其因数, 我们不断的寻找当前数因数并求积, 如果当前积大于n或找不到连续的因数时跳出, 并取最优的序列 看代码吧 !
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef long long LL;
const LL maxn = 50000;
LL n, tmp;
int main()
{
cin >> n;
int first = 0, len = 0, maxm = sqrt(n)+1;
for(int i = 2; i <= maxm; i++){
int j;
tmp = 1;
for(j = i; j <= maxm; j++){
tmp *= j;
if(n%tmp != 0) break; //超出或当前数不为因数
}
if(j - i > len)
len = j-i, first = i;
}
if(first == 0) //素数或1
cout << 1 << endl << n;
else{
cout << len << endl << first;
for(int i = 1; i < len; i++)
cout << '*' << first+i;
cout << endl;
}
return 0;
}