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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章