PAT Advanced 1096 Consecutive Factors (20) [数学问题-因子分解 逻辑题]

时间:2022-07-17 17:46:38

题目

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

567

题目分析

已知一个整数N,求所有N的连续因子因式分解中,最长连续因子个数和最小连续因子序列

注:最小连续因子序列的长度其实就是最长连续因子个数(因为连续因子序列的第一个数越大,连续因子序列越短)

解题思路

  1. 连续因子数

    1.1 若为0,表示N是质数,因子只有1和N本身

    1.2 若大于0

    1.2.1 若等于1,表示N因子分解后,一个因子<=sqr(n),一个因子>=(sqr(n))

    1.2.2 若大于1,表示N因子分解后,可以找到连续因子

易错点

  1. 注意连续因子数为0和连续因子树为1的不同情况区分
  2. 最小连续因子序列的长度其实就是最长连续因子个数(因为连续因子序列的第一个数越大,连续因子序列越短)

Code

#include <iostream>
#include <cmath>
using namespace std;
int main(int argc,char * argv[]) {
int n;
scanf("%d",&n);
int sqr=(int)sqrt(1.0*n);
int len = 0,first=0;
for(int i=2; i<=sqr; i++) {
int temp =1;
int j;
for(j=i; j<=sqr; j++) {
temp*=j;
if(n%temp!=0)break;
}
if(j-i>len) {
len=j-i;
first = i;
}
}
if(len==0) printf("1\n%d", n);
else {
printf("%d\n",len);
for(int i=first; i<first+len; i++) {
if(i!=first)printf("*");
printf("%d", i);
}
}
return 0;
}