您的位置:首页 > 其它

PAT 1096. Consecutive Factors (20)

2015-08-18 12:57 477 查看

1096. Consecutive Factors (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<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

最初将start的下一个设置为start = start + length + 1, 这种是错误的。而且这里用long long是因为start*start会超过int32表示的范围而不能跳出导致最后一个测试点运行超时


#include <iostream>
#include <cmath>

using namespace std;

int main()
{
long long num;
cin >> num;

long long start = 2, length = 0;
long long maxLength = 0, maxStart;
long long remain = num;
while (1)
{
if (remain % (start + length) != 0)
{
if (length > maxLength)
{
maxLength = length;
maxStart = start;
}
start++;
length = 0;
remain = num;
if (start*start > num)
break;
}
else
{
remain /= (start + length);
length++;
}
}

if (maxLength == 0)
{
cout << 1 << endl;
cout << num;
return 0;
}
cout << maxLength << endl;
for (long long i = 0; i < maxLength; i++)
{
cout << maxStart + i;
if (i < maxLength - 1)
cout << "*";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: