PAT (Advanced Level) Practise - 1096. Consecutive Factors (20)

 

http://www.patest.cn/contests/pat-a-practise/1096

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

 



此题是2015年春季的研究生入学考试复试时的机试题,链接 http://www.patest.cn/contests/graduate-entrance-exam-2015-03-20

此题不难,但是很多人没拿到分数,因为没有想到最简单的方法:暴力遍历。针对一个已确定是Factor的数tempfactor,进行如下处理:
while(num%tempfactor==0) templen++,num/=tempfactor,tempfactor++;
if(templen>maxlen) maxlen=templen,maxfactor=factors[i];
 1 #include<stdio.h>
 2 #include<math.h>
 3 
 4 int main()
 5 {
 6     int N=0;
 7     scanf("%d",&N);
 8     if(N==2 || N==3 || N==5)  {printf("1\n%d",N);return 0;}
 9     
10     int num=(int)sqrt(N),len=0,factors[1000000]={0};
11     for(int i=2;i<=num;i++)  if(N%i==0) factors[len]=i,len++; 
12     factors[len]=N,len++;
13     
14     int maxlen=0,maxfactor=N;
15     int templen=0,tempfactor=0;
16     for(int i=0;i<len;i++)
17     {
18             num=N,tempfactor=factors[i],templen=0;
19             while(num%tempfactor==0) templen++,num/=tempfactor,tempfactor++;  
20             if(templen>maxlen) maxlen=templen,maxfactor=factors[i];
21     }
22     
23     printf("%d\n",maxlen);    
24     for(int i=0;i<maxlen;i++)
25     {
26             if(i)  printf("*%d",maxfactor);
27             else  printf("%d",maxfactor);
28             maxfactor++;
29     }
30     return 0;    
31 }

 

posted on 2015-04-27 18:17  Asin_LZM  阅读(607)  评论(0编辑  收藏  举报