PAT甲级1096 Consecutive Factors (20分)|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:

在这里插入图片描述

​​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;
}
©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页