PAT 甲级 1096 Consecutive Factors(模拟)

1096 Consecutive Factors (20)(20 分)

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

分析 :

一道很简单的题目,但我自己给自己搞了不少bug出来,总之思路理清就没事。

C++:

#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<queue>
#include<set>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
int fun(int n,int k)
{
	int count=0,temp=n;
	for(int i=k;i<=n;i++){
		if(temp%i==0){
			count++;
			temp=temp/i;
			continue;
		}
		else
			break;
	}
	return count;
}
int main()
{
	int n,length=0,start;
	cin>>n;
	for(int i=2;i<=sqrt(n);i++){
	//这边注意下到根号即可,因为一个数的最大因子是不会超过本身的根号的(素数除外) 
		if(fun(n,i)>length){
			length=fun(n,i);
			start=i;
		}
	}
	if(length==0)//素数 
		cout<<1<<endl<<n<<endl;
	else if(length==1)//最大因子与最小因子相同的数,比如81(3),4(2) 
		cout<<1<<endl<<start<<endl;
	else{
		cout<<length<<endl<<start;
	 	for(int i=start+1;i-start<length;i++)
	 		cout<<"*"<<i;	 			
	} 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zpjlkjxy/article/details/81776440