PTA甲级 1096 Consecutive Factors (C++)

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 < 2 31 ) N (1<N<2^{31}) 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

Caution:

这道题有一个点我觉得有歧义,因为这道题实际是要求你列出来的因数必须同时是在一种因式分解下,不能是所有的因数看最长的连续子串,例如如果 N = 12 ,那么输出的应该是

2
2*3

而不是

3
2*3*4

因为2、3、4不能同时位于一个因式分解式子里。

另外一个需要注意的点就是不要遍历到 n ,要不然会超时,遍历到sqrt(n)就可以了。

Solution:

// Talk is cheap, show me the code
// Created by Misdirection 2021-08-13 11:49:23
// All rights reserved.

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

bool isPrime(int n){
    if(n <= 3) return true;
    int a = 2;

    while(a <= n / a){
        if(n % a == 0) return false;
        a++;
    }

    return true;
}

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

    if(isPrime(n)){
        printf("1\n%d\n", n);
        return 0;
    }

    // 不是素数
    int start = 2, maxLen = 0;
    for(int i = 2; i <= sqrt(n); ++i){
        if(n % i == 0){
            int j = i;
            int product = 1;

            while(j <= n){
                product *= j;
                if(n % product == 0) j++;
                else break;
            }

            if(j - i > maxLen){
                start = i;
                maxLen = j - i;
            }
        }
    }

    printf("%d\n", maxLen);

    for(int i = 0; i < maxLen; ++i){
        printf("%d", i + start);
        if(i == maxLen - 1) printf("\n");
        else printf("*");
    }


    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

负反馈循环

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值