1096. Consecutive Factors (20)
Among all the factors of a positive integer N, there may exist several consecutive numbers. For example, 630 can be factored as 3*5*6*7, where 5, 6, and 7 are the three consecutive numbers. Now given any positive N, you are supposed to find the maximum number of consecutive factors, and list the smallest sequence of the consecutive factors.
Input Specification:
Each input file contains one test case, which gives the integer N (1<N<231).
Output Specification:
For each test case, print in the first line the maximum number of consecutive factors. Then in the second line, print the smallest sequence of the consecutive factors in the format "factor[1]*factor[2]*...*factor[k]", where the factors are listed in increasing order, and 1 is NOT included.
Sample Input:630Sample Output:
3 5*6*7
求连续的因子。从2开始挨个时,看以哪个开头的连续因子数量最多,一直到sqrt(n)为止,不要到n,会超时。
注意:
因为是到sqrt(n)为止,所以如果给的是素数,则max最后是0,要特判输出。或者在一开始就对素数特判也可以,前边打印素数表或直接判定n是否为素数都可以。
#include <cstdio>
#include <cmath>
int n, max = 0, num, m, index = 0;
int main(){
scanf("%d", &n);
int range = floor(sqrt(n));
for(int i = 2; i <= range; i++){
num = 0, m = n;
int j = i;
while(m % j == 0){
m /= j;
j++;
num++;
}
if(num > max){
max = num;
index = i;
}
}
if(max == 0) printf("1\n%d", n);
else{
printf("%d\n", max);
for(int i = index; i < index+max; i++){
printf("%d", i);
if(i != index+max-1) printf("*");
}
}
return 0;
}