L1-006 连续因子 (20 分)

@[TOC](L1-006 连续因子 (20 分))

一个正整数 N 的因子中可能存在若干连续的数字。例如 630 可以分解为 3×5×6×7,其中 5、6、7 就是 3 个连续的数字。给定任一正整数 N,要求编写程序求出最长连续因子的个数,并输出最小的连续因子序列。

输入格式:
输入在一行中给出一个正整数 N(1<N<2^31)。

输出格式:
首先在第 1 行输出最长连续因子的个数;然后在第 2 行中按 因子1*因子2*……*因子k 的格式输出最小的连续因子序列,其中因子按递增顺序输出,1 不算在内。

输入样例:

630

输出样例:

3
5*6*7

遍历连续因子长度即可

11! = 39 916 800
12! = 479 001 600
2^31 = 2 147 483 648 约为2*10^9
连续因子最长,则第一个因子就要小,所以连续因子的最大长度为len为12

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <climits>
using namespace std;
typedef long long LL;
#define debug(x, y) cout<<x<<" "<<y<<endl
#define nl cout<<endl
#define fy cout<<"------"<<endl
const int maxn = 1010;
int main() {
    LL n, prd, sqrtn;
    cin>>n;
    sqrtn = (LL)sqrt(n);
    LL lft, len, rgt;
    ///lft为因子的第一个数,rgt=lft+len-1为最后一个。
    bool f=false;
    for(len=12; len>0; len--) {///找最长的,所以len递减
        for(lft=2; lft<=sqrtn; lft++) {
            ///连续因子序列要求最小,故令lft从2开始
            prd=1;
            rgt=lft+len-1;
            for(LL i=lft; i<=rgt; i++) prd*=i;
            if(n%prd==0) {
                f=true;
                break;
            }
        }
        if(f) break;
    }
    ///若f为false,则说明n没有除去1和自身以外的因子,n为质数
    if(!f) cout<<1<<endl<<n<<endl;
    else {
        cout<<len<<endl;
        for(int i=lft; i<lft+len; i++) {
            printf(i==lft ? "%d" : "*%d", i );
        }
        nl;
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_44379458/article/details/88899638
今日推荐