PAT-A-1096 Consecutive Factors 【因数分解】

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

要从2开始遍历到sqrt(n),一定要取等号,即i<=sqrt(n)。最后要注意质数的情况。若最后遍历完后,存储的向量为空,应该将n作为结果输出。

#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int main(){
	int n;
	int num=0;                //保存最长连续银子数
	scanf("%d",&n);
	vector<int> data;        //保存结果
	for(int i=2;i<=sqrt(n);i++){     
		int tempN=n;
		int j=i; 
		int tempNum=0;         //以i为起点的连续因子数
		vector<int> tempres;   //临时结果
		while(tempN%j==0){     //是因子
			tempNum++;         
			tempN/=j;          //变换tempN
			tempres.push_back(j);
			j++;
		}
		if(tempNum>num){        //如果本次计算的连续因子数大于已经保存的,就替换
			num=tempNum;
			data.clear();
			data.assign(tempres.begin(),tempres.end());  //assign赋值
		}
	}
	if(data.size()==0){
		data.push_back(n);
	}
	printf("%d\n",data.size());
	printf("%d",data[0]);
	for(int k=1;k<data.size();k++){
		printf("*%d",data[k]);
	}
	return 0;
}

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读