您的位置:首页 > 其它

浙江大学PAT_甲级_1096. Consecutive Factors (20)

2015-08-18 16:45 501 查看
题目链接:点击打开链接

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
5*6*7

我的C++代码:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
long long n=2;
cin >> n;
vector<int> finally_factors(1,n), temp_factors;  //finally_factors(1,n)最终因子,目前只有一个元素n
int component_n;//n的分解部分
for (long long i = 2; i*i <= n; i++)  //从2开始,求因子
{
temp_factors.clear();//清除旧的因子
component_n = n;
for (long long j = i; j <=31; j++)  //循环求因子
{
if (component_n%j == 0)//被整除,是因子
{
temp_factors.push_back(j);//记录下来
component_n = component_n /j;//component_n =商
}
else
break;//不被整除,因子不连续,则结束
}
if (temp_factors.size()>finally_factors.size())  //保留最长的因子集合
finally_factors = temp_factors;
else if (temp_factors.size() == finally_factors.size() && temp_factors[0]<finally_factors[0])//保留最小序列
finally_factors = temp_factors;
}
cout << finally_factors.size() << endl;  //输出连续因子个数
cout << finally_factors[0];//输出连续因子
for (int i = 1; i<finally_factors.size(); i++)
cout << "*" << finally_factors[i];
//system("pause");
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: