题意
给出一个数字n( 1 < n < 2 31 1<n<2^{31} 1<n<231),计算最长的连续和数,如果两个长度相同,选择开始较小的那串。按格式输出。
思路
- 首先 2 31 = 2 , 147 , 483 , 648 > 1 E 9 2^{31} = 2,147,483,648 >1E9 231=2,147,483,648>1E9,而题目要求400ms。在C++中1s能运行1E7-1E8次,所以一定不能枚举,得找数学规律优化时间复杂度。
- 然后找数学规律。
- 由连续相乘,首先思考len = 1的情况:这个因子要么是n本身(n为质数),要么 <= sqrt(n)(n = a1 * (n/a1))
- 而如果len > 1则n = (a1 * a2 * … * ak) * (n / a),这种情况a1 < sqrt(n);
- 综上,可以在2 - sqrt(n)循环中找,于是代码如下。
解法
#include<bits/stdc++.h>
using namespace std;
int n, mcnt = 0, msta;
int main(){
cin>>n;
for(int i = 2; i <= sqrt(n); i++){
if(n % i != 0) continue;
else {
int tar = n, cnt = 0, sta = i;
while(tar % sta == 0)
tar /= sta++, cnt ++;
if(cnt > mcnt)
mcnt = cnt, msta = i;
}
}
if(mcnt == 0) cout<<1<<endl<<n;
else{
cout<<mcnt<<endl;
for(int i = 0; i < mcnt; i ++){
if(i != 0) cout<<"*";
cout<<msta + i;
}
}
}
原题
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