PAT甲级1096 Consecutive Factors (20分)|C++实现

该博客介绍了一种算法,用于寻找给定正整数的最大连续因子序列。通过双重循环遍历并计算连续数的乘积,检查是否为输入数的因子,更新最大连续因子数和对应序列。当找到的连续因子数大于当前最大值时,更新答案。对于素数情况,直接输出其本身。
摘要由CSDN通过智能技术生成

一、题目描述

原题链接
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:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

Sample Input:

630

Sample Output:

3
567

二、解题思路

找一个数的连续因子序列最大长度以及对应的序列,这道题时间给的比较宽容,400ms,我们可以建立一个二重循环,遍历2到 N \sqrt{N} N ,之后再在里面建立一个循环,不断计算连续数的累乘,检查是否能整除N,之后对答案进行更新即可。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
int main()
{
  int mx = 0;
  long long i, j, N;
  vector<int> ans;
  scanf("%lld", &N);
  for(i=2; i*i <= N; i++)   //题目要求最小序列,那么不可能有两个满足i*i>N的因子
  {
    int cnt = 0;    //连续因子的个数
    long long sum = 1;  //连续因子的乘积
    vector<int> tmp;
    for(j=i; ; j++) //
    {
      sum *= j; //连续乘积
      if(N%sum == 0)    //可以被整除
      {
        tmp.push_back(j);
        cnt++;
      }
      else  //不能被整除,更新答案,退出循环
      {
        if(cnt > mx)    //更新答案
        {
          mx = cnt;
          ans = tmp;
        }
        break;
      }
    }
  }
  if(mx == 0)   //N为素数
  {
    printf("1\n%d", N);
    return 0;
  }
  printf("%d\n", mx);
  for(int k=0; k<ans.size(); k++)
  {
    if(k==0)	printf("%d", ans[0]);
    else	printf("*%d", ans[k]);
  }
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值