PAT 1096. Consecutive Factors (20)

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

最初将start的下一个设置为start = start + length + 1, 这种是错误的。而且这里用long long是因为start*start会超过int32表示的范围而不能跳出导致最后一个测试点运行超时
 1 #include <iostream>
 2 #include <cmath>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     long long num;
 9     cin >> num;
10 
11     long long start = 2, length = 0;
12     long long maxLength = 0, maxStart;
13     long long remain = num;
14     while (1)
15     {
16         if (remain % (start + length) != 0)
17         {
18             if (length > maxLength)
19             {
20                 maxLength = length;
21                 maxStart = start;
22             }
23             start++;
24             length = 0;
25             remain = num;
26             if (start*start > num)
27                 break;
28         }
29         else
30         {
31             remain /= (start + length);
32             length++;
33         }
34     }
35 
36     if (maxLength == 0)
37     {
38         cout << 1 << endl;
39         cout << num;
40         return 0;
41     }
42     cout << maxLength << endl;
43     for (long long i = 0; i < maxLength; i++)
44     {
45         cout << maxStart + i;
46         if (i < maxLength - 1)
47             cout << "*";
48     }
49 }

 

posted @ 2015-08-18 12:57  JackWang822  阅读(335)  评论(0编辑  收藏  举报