【PAT】A1096. Consecutive Factors (20)

Description:
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

暴力法:

//NKW 甲级真题1007
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
using namespace std;
vector<int> vi, vt;
int main(){
	int n, cnt, rcnt = -1, num;
	scanf("%d", &n);
	for (int i = 2; i <= sqrt(n); i++){    //连乘的第一个数
		cnt = 0;
		num = n;
		vt.clear();
		for (int j = i; j <= n; j++){
        //这里如果写成j<=sqrt(n)也能通过,但是其实有问题,如输入6 输出为1\n2,因为3>sqrt(6)
			if (num%j == 0){
				num /= j;
				vt.push_back(j);
				cnt++;
			}
			if (j - i + 1 != cnt)	break;
		}
		if (cnt > rcnt){
			rcnt = cnt;
			vi.clear();
			vi = vt;
		}
	}
	if (vi.size()){
		printf("%d\n", vi.size());
		for (int i = 0; i < vi.size(); i++){
			if (i)	printf("*");
			printf("%d", vi[i]);
		}
	}
	else	printf("1\n%d", n);
	printf("\n");
	system("pause");
	return 0;
}

程序分析:

本题使用暴力法求解,没有用什么算法所以对循环的条件需要抠一抠。最暴力的解法的写法是本程序12行和16行写成:

12    i<=n

16    j<=n

但是这样超时了。

所以经过思考,对于12行可以改为i<=sqrt(n),这是因为,i是我们连乘的第一个数,本题要求在连乘长度相同时首位取最小。如果i>sqrt(n),那么这个情况下连乘的长度为1(显然此时i=n)。显然Len(i>sqrt(n))<=Len(i<=sqrt(n)),故我们只需要考虑i<=sqrt(n)的情况即可。

而对于16行,最初我想当然的也改为了j<=sqrt(n),在NKW和PTA上也都通过了,但是我无聊试了一下6和20,突然发现结果是:1\n2和1\n4   (这是我偷懒的写法,相信大家都懂是什么意思)

这显然不对,正确的结果应该是2\n2*3和2\n4*5。我还发现《算法笔记——上级实战训练》(2018年1月第一版P219)上有这样一句话:

我想了想,3>sqrt(6)=2.44,6可以被3整除。这~~~~~

所以在我写的这个程序里,还是使用j<=n,当然啦,我这样写能够通过。

猜你喜欢

转载自blog.csdn.net/ztmajor/article/details/81137814