1096 Consecutive Factors (20分)
如果 a * (a + 1) * (a + 2) * ... * (a + k) 是n的因子,且没有比其更长的因子了,与其相等的因子第一个数也大于a (a > 1),则a * (a + 1) * (a + 2) * ... * (a + k)就是要找的结果
由于要找的序列是个连续序列,因此更新的时候只需要记录起始位置和序列长度即可. !!!
写法一:
while(n % temp == 0){
len++;
++j;
temp *= j;
}
写法二:
while(n % j == 0){
len++;
++j;
}
写法一正确,而写法二错误,因为对于12这种写法一得出的连续因子是3*4,而写法二得出的连续因子是2*3*4
#include<iostream>
#include<cmath>
using namespace std;
int main(){
int ansI = 0,ansLen = 0,j,tmp,n;
cin>>n;
int sqr = sqrt(n);
for (int i = 2; i <= sqr;++i){
if (n % i == 0){
tmp = 1,j = i;
while(1){
tmp *= j;
if (n % tmp) break;
if (ansLen < j - i + 1){ // 更新起始点和序列长度即可,因为是连续的
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)
cout<<'*'<<ansI + i;
else cout<<ansI;
}
return 0;
}