[PAT]1096 Consecutive Factors (20分)(样例3、5、6未过原因)

一、题目

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).
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

二、题目翻译

(这道题我第一次做题意读错了,看来英语还是很重要。)
在一个正整数N的所有因子之中,可能会存在几个连续的整数。例如:630可以被因式分解为3 * 5 * 6 * 7,可以看到5、6、7就是一串连续的整数。现在给出一个正整数N,要求你找到满足上述条件的最长的序列,如果存在多个相同长度的序列那么就选择首个数字最小的序列(序列中不包括数字1)。
说人话就是:给出一个正整数N,将其进行因式分解,找到所有因式分解中存在连续整数的最长的序列(不包括数字1)。(说的好像也不算是人话。。。)
我第一次理解成了,找到正整数N所有因子当中连续的数列,然后就好几个样例没有通过。
这里举例:比如N=12,那么应该输出的结果是

2
2*3

如果按照我第一次理解的输出应该是:

3
2*3*4

很明显就错了嘛。。。
另外这道题目很像19年北航考研上机考试题目点击这里查看

三、代码

#include <iostream>
#include <vector>
#include <fstream>
#include <tgmath.h>

using namespace std;
long long int N;
vector<int> ans;
vector<int> temp_ans;

int main() {
//    fstream cin("in");
    cin >> N;
    ans.clear();
    temp_ans.clear();

    for (int i = 2; i <= sqrt(N)+1; ) {
        if (N % i == 0) {
            temp_ans.clear();
            temp_ans.push_back(i);
            int factor = i;
            factor ++;
            long long int temp_f = i * factor;
            while (N%temp_f==0){
                temp_ans.push_back(factor);
                factor ++;
                temp_f *= factor;
            }
            if(temp_ans.size() > ans.size()){
                ans = temp_ans;
            }
            i ++;
        } else {
            i ++;
            continue;
        }
    }

    if(ans.size()==0){
        cout<<"1"<<endl;
        cout<<N;
        return 0;
    }

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

四、注意

样例3未通过的原因:在for循环里遍历时,需要从i=2,步长为1,挨个遍历,不能因为中间找到了满足题目要求的序列就使得i = factor+1,不然样例3会通过不了。这是因为:假设存在序列{a1、a2、a3}满足N = x1 * a1 * a2 * a3 * x2,但是也有可能N = a2 * a3 * a4 * a5,那么正确的解就不是{a1、a2、a3}而是{a2、a3、a4、a5}了。
样例5、6未通过的原因:样例5、6是质数,只能分解为1 * N所以要输出

1
N//这里不是字母N,而是输入的正整数N
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值