1. 程式人生 > >PAT1096:Consecutive Factors

PAT1096:Consecutive Factors

cout math.h for min strong specific rt+ line file

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

思路
因為12! < 2^31 < 13!。
所以,因子大小不會超過12!,連續因子的長度不會超過12。
從長度為12開始減小,令res為滿足條件的最大因子,窮舉所有可能直到滿足N % res == 0就行。
註:窮舉的過程中res會溢出,不過不影響結果。。
代碼
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    int N;
    while(cin >> N)
    {
        int maxnum = sqrt(N);
        for(int len = 12;len >= 1;len--)
        {
            for(int start = 2; start <= maxnum;start++)
            {
               int res = 1;
               for(int i = start;i - start < len;i++)
               {
                   res *= i;
               }
               if(N % res == 0)
               {
                   cout << len << endl << start;
                   for(int j = start + 1;j - start < len;j++)
                    cout << "*" << j;
                   return 0;
               }
            }
        }
        cout << 1 << endl;
        cout << N;
    }
}

  

PAT1096:Consecutive Factors