【刷题】L1-006 连续因子-PAT团体程序设计天梯赛

版权声明:转载先点个赞嘛~~ https://blog.csdn.net/qq_39011762/article/details/88080757

L1-006 连续因子 (20 分)

一个正整数 N 的因子中可能存在若干连续的数字。例如 630 可以分解为 3×5×6×7,其中 5、6、7 就是 3 个连续的数字。给定任一正整数 N,要求编写程序求出最长连续因子的个数,并输出最小的连续因子序列。
输入格式:
输入在一行中给出一个正整数 N 1 < N < 2 31 ) N(1<N<2^{31})
输出格式:
首先在第 1 行输出最长连续因子的个数;然后在第 2 行中按 1 2 k 因子1*因子2*……*因子k 的格式输出最小的连续因子序列,其中因子按递增顺序输出,1 不算在内。
输入样例:
630
输出样例:
3
5*6*7

分析:暴力枚举,将 i i 从2枚举到 n \sqrt{n} 对于每个 i i 往后寻找连续因子,记录下最大长度
注意:这样枚举的上限是 n + 1 \sqrt{n} + 1 ,否则有一个测试点无法通过

#include<iostream>
#include<cstdio>
#include<vector>
#include<map>
#include<string>
#include<stack>
#include<queue>
#include<set>
#include<algorithm>
#include<cmath>
using namespace std;
int main()
{
    int n, lmax = 0, imax;;
    cin>>n;
    int sqr = (int)sqrt(1.0 * n);
    for(int i = 2; i <= sqr + 1; ++i){
        long long int prod = 1;
        int l = 0;
        for(int j = i; j <= sqr + 1; ++j){
            prod *= j;
            if(n % prod != 0){
                if(l > lmax){
                    lmax = l; imax = i;
                }
                break;
            }
            l++;
        }
    }
    if(lmax == 0)printf("1\n%d", n);
    else{
        printf("%d\n%d", lmax, imax);
        for(int i = imax + 1; i < imax + lmax; ++i)printf("*%d", i);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39011762/article/details/88080757