PAT 1096.Consecutive Factors

1096. Consecutive Factors (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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:
630
Sample Output:
3
5*6*7

题目分析:
输入一个整数,输出它的连续因数的最大个数,若是个数相同则输出小的序列。1不算但自身是计算的,也就是质数的结果为自身。
由于一个整数除自身外最大的因数不能超过该数的开方值,所以先将2~sqrt(n)之间的因数保存到数组中,然后保存该数自身。遍历这个因数数组,若以该数开始存在连续的因数序列,则判断是否是最长的序列,若在某一值中断则进度下一个因数。
 1 #include<stdio.h>
 2 #include<algorithm>
 3 #include<vector>
 4 
 5 using namespace std;
 6 
 7 int main(void){
 8     int in;
 9     int temp;
10     vector<int> res, now, factor;
11     int i, j;
12     scanf("%d", &in);
13     int n = (int)sqrt(in) + 2;
14     for (i = 2; i <= n; i++){
15         if (in%i == 0)
16             factor.push_back(i);
17     }
18     factor.push_back(in);
19     for (i = 0; i < factor.size(); i++){
20         temp = in;
21         for (j = factor[i]; j <= in; j++){
22             if (temp%j == 0){
23                 now.push_back(j);
24                 temp /= j;
25             }
26             else{
27                 break;
28             }
29         }
30         if (now.size() > res.size()){
31             res = now;
32         }
33         now.clear();
34     }
35     
36     printf("%d\n", res.size());
37     for (i = 0; i < res.size(); i++){
38         printf("%d", res[i]);
39         if (i == res.size() - 1){
40             printf("\n");
41         }
42         else{
43             printf("*");
44         }
45     }
46     return 0;
47 }

 

posted @ 2018-02-04 12:45  GrayWind  阅读(104)  评论(0)    收藏  举报