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
解题思路:
给出一个整数,要你求其最多的连续因子个数,以及其因子。首先我们知道,一个数n一定不会被大于的数整除,因此我们只需要遍历2~
的数,求此时n能最多被多少个连续整数的乘积整除。
注意:如果遍历结束后发现中不存在能整除n的连续整数,因此答案就是n本身。
#include<iostream>
#include<math.h>
using namespace std;
#define ll long long
int main()
{
ll n;
ll maxlen = 0, pos = 0;
cin >> n;
for (ll i = 2; i < sqrt(n); i++)
{
ll product = 1; //当前连续整数的乘积
ll j = i;
while (1)
{
product *= j;
if (n%product != 0) //不能整除结束
break;
if (j - i + 1 > maxlen) //更新最大长度
{
pos = i;
maxlen = j - i + 1;
}
j++;
}
}
if (maxlen == 0)
{
cout << 1 << endl << n << endl;
}
else
{
cout << maxlen << endl;
for (ll i = 0; i < maxlen; i++)
{
cout << pos++;
if (i < maxlen - 1)
cout << "*";
}
}
return 0;
}