1096. Consecutive Factors (20)-PAT甲级真题

给定一个不超过2^31的正整数n,计算最长的连续因子序列。若存在多个相同长度的序列,选择起始值较小的那个。文章提到,由于数据范围,无法使用枚举法,需要通过数学规律优化算法。解决方案是从2到平方根(n)迭代,查找因子,找到最大连续因子序列的长度和起始值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意

给出一个数字n( 1 < n < 2 31 1<n<2^{31} 1<n<231),计算最长的连续和数,如果两个长度相同,选择开始较小的那串。按格式输出。

思路

  • 首先 2 31 = 2 , 147 , 483 , 648 > 1 E 9 2^{31} = 2,147,483,648 >1E9 231=2,147,483,648>1E9,而题目要求400ms。在C++中1s能运行1E7-1E8次,所以一定不能枚举,得找数学规律优化时间复杂度。
  • 然后找数学规律。
    • 由连续相乘,首先思考len = 1的情况:这个因子要么是n本身(n为质数),要么 <= sqrt(n)(n = a1 * (n/a1))
    • 而如果len > 1则n = (a1 * a2 * … * ak) * (n / a),这种情况a1 < sqrt(n);
  • 综上,可以在2 - sqrt(n)循环中找,于是代码如下。

解法

#include<bits/stdc++.h>
using namespace std;
int n, mcnt = 0, msta;
int main(){
    cin>>n;
    for(int i = 2; i <= sqrt(n); i++){
        if(n % i != 0) continue;
        else {
            int tar = n, cnt = 0, sta = i;
            while(tar % sta == 0)
                tar /= sta++, cnt ++;
            if(cnt > mcnt)
                mcnt = cnt, msta = i;
        }
    }
    if(mcnt == 0) cout<<1<<endl<<n;
    else{
        cout<<mcnt<<endl;
        for(int i = 0; i < mcnt; i ++){
            if(i != 0) cout<<"*";
            cout<<msta + i;
        }
    }
}

原题

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<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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值