1096. Consecutive Factors (20)

题目链接:http://www.patest.cn/contests/pat-a-practise/1096
题目:

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

分析:
题意是说在所有连乘的因数中找最大最长串,注意这里不是对所有的因数遍历,而是对乘积为给定数的数中找,比如12,最长就是2,3*4,而不是3,2*3*4。
参考资料:
http://www.cnblogs.com/asinlzm/p/4460935.html

AC代码:
#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<stack>
#include<string>
#include<string.h>
#include<map>
#include<cmath>
using namespace std;
int main(){
 //freopen("F://Temp/input.txt", "r", stdin);
 int N = 0;
 cin >> N;
 if (N == 2 || N == 3 || N == 5)  { printf("1\n%d", N); return 0; }
 int num = (int)sqrt(N), len = 0, factors[1000000] = { 0 };
 for (int i = 2; i <= num; i++)  if (N%i == 0) factors[len] = i, len++;
 factors[len] = N, len++;
 int maxlen = 0, maxfactor = N;
 int templen = 0, tempfactor = 0;
 for (int i = 0; i<len; i++){//好解法
  num = N, tempfactor = factors[i], templen = 0;
  while (num%tempfactor == 0) templen++, num /= tempfactor, tempfactor++;
  if (templen>maxlen) maxlen = templen, maxfactor = factors[i];<span style="font-family: 微软雅黑; font-size: 14px; widows: auto;">//这里用的是逗号来完成多个语句的赋值</span>
 }
 printf("%d\n", maxlen);
 for (int i = 0; i<maxlen; i++)
 {
  if (i)  printf("*%d", maxfactor);//这种格式化输出的方法很好
  else  printf("%d", maxfactor);
  maxfactor++;
 }
 printf("\n");
 return 0;
}


截图:

——Apie陈小旭

你可能感兴趣的:(1096. Consecutive Factors (20))