首页 > 代码库 > 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
这道题是一个模式识别的问题。关于因数的问题,便利的方法是把所有因数找出来,并放在一个数组中。这就是这个问题的答案空间。
而模式识别的关键,就是一个双重循环。第一层是模式的起点,第二层是具体模式的寻找。类似于字符串匹配工作。
另一个注意点是分类解答。
#include <iostream> #include <vector> #include <math.h> using namespace std; int N; int lenth=1; int dot; int res=1; vector<int> V; int main() { cin >> N; for (int i = 2; i < sqrt(N) + 1; i++) { if (N%i == 0) { V.push_back(i); //cout << i << endl; } } //cout << endl; int templen=1; int maxdot = 0; int flag = 0; //res = V[0]; if (V.size() > 0) { for (int i = 0; i < V.size(); i++) { res = V[i]; templen = 1; for (int j = i+1; j < V.size(); j++) { if (V[j] - V[j - 1] == 1 && N % (V[j] * res) == 0) { flag = 1; //cout << V[i] << endl; templen++; if (templen > lenth) { lenth = templen; maxdot = i; } res *= V[j]; } else { templen = 0; //res = 1; break; } } } } if (V.size() == 0) { cout << "1" << endl << N; } else if (flag == 0) cout << "1" << endl << V[0]; else { cout << lenth << endl << V[maxdot]; for (int i = maxdot + 1; i < lenth + maxdot; i++) cout << "*" << V[i]; } return 0; }
1096. Consecutive Factors (20)