#1096. Consecutive Factors【数论 + 模拟】

原题链接

Problem Description:

Among all the factors of a positive integer N N N, there may exist several consecutive numbers. For example, 630 630 630 can be factored as 3 × 5 × 6 × 7 3\times 5\times 6\times 7 3×5×6×7, where 5, 6, and 7 are the three consecutive numbers. Now given any positive N N 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 N N ( 1 < N < 2 31 1<N<2^{31} 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

Problem Analysis:

题目要求我们求给定数 n n n 的最大连续因子的序列,我们可以采用枚举的思想,由于因子不能包含 1 1 1,因此我们可以枚举起始因子 k k k,然后枚举连续因子的长度: k ⋅ ( k + 1 ) ⋅ ( k + 2 ) ⋯ k\cdot (k + 1) \cdot (k + 2) \cdots k(k+1)(k+2),由于一个数的约数总时成对出现在 n \sqrt n n 左右,因此起始位置只需要从区间 [ 2 , n ] [2, \sqrt n] [2,n ] 中枚举即可。

Code

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>

using namespace std;

int main()
{
    
       
    int n;
    cin >> n;

    vector<int> res;
    for (int i = 2; i <= n / i; i ++ )
        if (n % i == 0) // i是满足条件的一个其实位置
        {
    
    
            vector<int> seq;
            for (int m = n, j = i; m % j == 0; j ++ ) // 从i开始往后枚举连续的因子
            {
    
    
                seq.push_back(j);
                m /= j;
            }

            if (seq.size() > res.size()) res = seq;
        }

    cout << res.size() << endl;
    
    for (int i = 0; i < res.size(); i ++ )
    {
    
    
        cout << res[i];
        if (i != res.size() - 1) cout << "*";
    }
    cout << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/geraltofrivia123/article/details/121130919