题目:click me~
题意:给出整数N,需要找到连续因子的最大个数,若有多个,输出第一个数最小的那个序列。
解题思路:
步骤一:首先注意到,N不会被除自己外的大于sqrt(N)的整数整除,因此只需要从2~sqrt(N)遍历连续整数的第一个,求此时N能被最多多少个连续整数的乘积整除。在此过程中,如果发现长度比当前最长长度anslen更长的情况(anslen初始化为0),就更新anslen和对应第一个整数ansi。
步骤二:若遍历结束后anslen还是等于0,那么说明答案就是N本身;否则,输出[ansi,ansi+anslen)区间内的整数。
code
#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
typedef long long LL;
int main() {
LL n;
cin >> n;
LL sqr = (LL)sqrt(1.0*n);
LL ansi=0, anslen=0;//anslen为最长连续整数个数,ansi为对应的第一个整数
for (LL i = 2;i <= sqr;i++) {
LL temp = 1, j = i;//temp为当前连续整数的乘积
while (1) {
temp *= j;
if (n%temp != 0)break;//若不能整除,则结束计算
if (j - i + 1 > anslen) {//发现了更长的长度
ansi = i;//更新
anslen = j - i + 1;
}
j++;//下一个整数
}
}
if (anslen == 0)cout << "1" << endl << n;
else {
cout << anslen << endl;
for (int i = 0;i < anslen;i++) {
if (i != 0)cout << "*";
cout << ansi + i;
}
}
return 0;
}