1096. Consecutive Factors (20)——PAT (Advanced Level) Practise

版权声明:本文为博主原创文章,转载请标明出处 http://blog.csdn.net/xianyun2009 https://blog.csdn.net/xianyun2009/article/details/51407851

题目信息

1096. Consecutive Factors (20)

时间限制400 ms
内存限制65536 kB
代码长度限制16000 B
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

解题思路

分奇偶两种情况讨论

AC代码

#include <algorithm>
#include<set>
#include<queue>
#include<map>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
using namespace std;

void dfsFactor(long long n, long long preNum, vector<int>&factor, vector<vector<int>>&ans,int&factorSize)
{
    if (n % (preNum + 1) == 0)
    {
        factor.push_back(preNum + 1);
        dfsFactor(n / (preNum + 1), preNum + 1, factor, ans, factorSize);
    }
    else if (!factor.empty() && factor.size() > factorSize)
    {
        factorSize = factor.size();
        ans.push_back(factor);
    }
}
bool cmp(const vector<int>&a, const vector<int>&b)
{
    if (a.size() > b.size())
        return true;
    else if (a.size() == b.size() && a[0] < b[0])
        return true;
    else return false;
}
int main(void)
{
    int n;
    cin >> n;
        if (n % 2 == 1)
        {
            int temp = (int)((double)sqrt(n) + 1);
            for (int i = 2; i <= temp; ++i)
            {
                if (n%i == 0)
                {
                    cout << "1" << endl;
                    cout << i << endl;
                    return 0;
                }
            }
            cout << "1" << endl;
            cout << n << endl;

        }
        else
        {
            vector<int> maxFactor = { INT_MAX, n, (int)((double)sqrt(n) + 1), 1290, 215, 73, 35, 21, 14, 10, 0 };//3~13
            vector<int> factor(0);
            vector<vector<int>>ans(0);
            int factorSize = 0;

            for (long long i = 1; i <= min(n, maxFactor[factorSize + 1]); i++)
            {
                if (n % (i + 1) == 0)
                {
                    dfsFactor(n, i, factor, ans, factorSize);
                    factor.clear();
                }
            }
            sort(ans.begin(), ans.end(), cmp);
            cout << ans[0].size() << endl;
            for (int i = 0; i < ans[0].size(); i++)
            {
                cout << ans[0][i];
                if (i != ans[0].size() - 1)
                    cout << "*";
            }
            cout << endl;
        }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xianyun2009/article/details/51407851