团体程序设计天梯赛 L1-006. 连续因子

Two ways:

1.接近O(n)

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <math.h>
 4 
 5 int main()
 6 {
 7     long n,i,j,k,num=0,b;
 8     scanf("%ld",&n);
 9     for (i=2;i<=(long)sqrt(n);i++)
10     {
11         k=n;
12         for (j=i;;j++)
13             if (k%j==0)
14                 k=k/j;
15             else
16                 break;
17         if (j-i>num)
18         {
19             num=j-i;
20             b=i;    
21         }
22     }
23     if (num==0)
24     {
25         num=1;
26         b=n;
27     }
28     printf("%ld\n",num);
29     for (i=b;i<b+num;i++)
30     {
31         printf("%ld",i);
32         if (i!=b+num-1)
33             printf("*");
34     }
35     return 0;
36 }

 

2.O(kn) 会超时

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <math.h>
 4 
 5 int main()
 6 {
 7     long n,i,j,k,num=0,b;
 8     scanf("%ld",&n);
 9     for (i=2;i<=(long)sqrt(n);i++)
10     {
11         k=n;
12         for (j=i;;j++)
13             if (k%j==0)
14                 k=k/j;
15             else
16                 break;
17         if (j-i>num)
18         {
19             num=j-i;
20             b=i;    
21         }
22     }
23     if (num==0)
24     {
25         num=1;
26         b=n;
27     }
28     printf("%ld\n",num);
29     for (i=b;i<b+num;i++)
30     {
31         printf("%ld",i);
32         if (i!=b+num-1)
33             printf("*");
34     }
35     return 0;
36 }

 

#include <stdio.h>#include <stdlib.h>#include <math.h>
int main(){long n,i,j,k,num=0,b;scanf("%ld",&n);for (i=2;i<=(long)sqrt(n);i++){k=n;for (j=i;;j++)if (k%j==0)k=k/j;elsebreak;if (j-i>num){num=j-i;b=i;}}if (num==0){num=1;b=n;}printf("%ld\n",num);for (i=b;i<b+num;i++){printf("%ld",i);if (i!=b+num-1)printf("*");}return 0;}

 

posted @ 2018-03-15 16:50  congmingyige  阅读(232)  评论(1编辑  收藏  举报