标签:连续 sum %s NPU 左右 记录 example include code
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
题意:找出整数的连续因子
思路:用queue保存整数的连续因子, l,r保存第一个连续因子和最后一个连续因子, maxx保存连续因子的最长长度, sum记录连续因子的和
如果n%sum!=0, 则表示连续因子中断,把queue清空,sum设置为1;
如果n%num==0,表示为连续因子,和max比较,更新maxx以及左右端点
因为是连续的数相乘,相当于阶乘,长度不会超过30;
注意点: 应该用long来保存整数,否则最后一个测试点会超时
maxx的初始值为0, 但是给出的数可能是素数,对于这种情况单独处理;
1 #include<iostream> 2 #include<queue> 3 #include<cmath> 4 using namespace std; 5 int main(){ 6 long n, i, sum=1, maxx=0, l=0, r=0; 7 cin>>n; 8 queue<int> q; 9 l=r=n;11 for(i=2; i<30; i++){ 12 sum *= i; 13 q.push(i); 14 while(n%sum!=0){ 15 sum /= q.front(); 16 q.pop(); 17 } 18 if(q.size()>maxx){ 19 maxx = q.size(); 20 l=q.front(); 21 r=q.back(); 22 } 23 24 } 25 if(l==r) maxx=1; 26 cout<<maxx<<endl; 27 for(i=l; i<=r; i++){ 28 if(i==l) cout<<l; 29 else printf("*%d", i); 30 } 31 return 0; 32 }
PAT 1096 Consecutive Factors (20)
标签:连续 sum %s NPU 左右 记录 example include code
原文地址:https://www.cnblogs.com/mr-stn/p/9217379.html