# PAT Advanced 1096 Consecutive Factors: Examine Factor One by One

## Overview

PAT Advanced 1096 Consecutive Factors: Examine factors one by one starting from 2 and the consecutive sequence, keep the one with the maximum length.

## PAT Advanced 1096 Consecutive Factors

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```

## Solution: Examine Factor One by One

I actually do not have smart fancy algorithm to solve this problem, my way is to brute force examine every possible starting factor from 2, and then check the longest possible consecutive factor sequence from that starting number, and keep record of the longest one, so the time complexity would be O(N^2) multiplication operations. The following C++ code could be accepted by PAT OJ to pass this 1096 Consecutive Factors problem:

```#include <cstdio>
#include <vector>
#include <cmath>

using std::vector;

typedef int T;

int main() {
T n;
scanf("%d", &n);

T limit = sqrt(n) + 1;
vector<T> result;
result.push_back(n);
vector<T> local;

for (T i = 2; i < limit; ++i) {
T tmp = n;
T factor = i;
local.clear();

while (tmp % factor == 0) {
local.push_back(factor);
tmp /= factor++;
}
if (local.size() > result.size()) {
result = local;
} else if (local.size() == result.size()) {
if (local[0] < result[0]) {
result = local;
}
}
}
printf("%d\n", result.size());
bool init = true;
for (const auto & f : result) {
if (init) {
printf("%d", f);
init = false;
} else {
printf("*%d", f);
}
}
printf("\n");
return 0;
}

```

And be careful about some special cases like n = 3, n = 4, n = 5.

## Summary

PAT Advanced 1096 Consecutive Factors: Examine factors one by one starting from 2 and the consecutive sequence, keep the one with the maximum length.

Written on May 30, 2015