PTAL1-006 连续因子解题报告---DFS

版权声明:转载请注明出处:https://blog.csdn.net/qq1013459920 https://blog.csdn.net/qq1013459920/article/details/85041863

                                     L1-006 连续因子 (20 分)

一个正整数 N 的因子中可能存在若干连续的数字。例如 630 可以分解为 3×5×6×7,其中 5、6、7 就是 3 个连续的数字。给定任一正整数 N,要求编写程序求出最长连续因子的个数,并输出最小的连续因子序列。

输入格式:

输入在一行中给出一个正整数 N(1<N<2​31​​)。

输出格式:

首先在第 1 行输出最长连续因子的个数;然后在第 2 行中按 因子1*因子2*……*因子k 的格式输出最小的连续因子序列,其中因子按递增顺序输出,1 不算在内。

输入样例:

630

输出样例:

3
5*6*7

题意:找一个正整数的最长连续因子 

素数的因子只有1和其本身,本题中1不算在因子内

最后一个测试点很坑,一定要用sqrt函数去开平方,不然会超时(19分) 

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cctype>
#include<map>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
bool is_prime(int x) {
	if (x == 1) return false;
	if (x == 2 || x == 3) return true;
	if (x % 6 != 1 && x % 6 != 5) return false;
	for (int i = 5; i <= sqrt(x); i += 6) {
		if (x % i == 0 || x % (i + 2) == 0)
			return false;
	}
	return true;
}
int dfs(int v, int fac, int len) {	//v被除数,fac因子,len连续长度
	if (v % fac == 0) {
		return dfs(v / fac, fac + 1, len + 1);
	}
	else return len;
}
int main() {
	int n;
	scanf("%d", &n);
	if (is_prime(n)) {
		printf("1\n%d\n", n);
		return 0;
	}
	int maxl = 0, res;
	for (int i = 2; i <= sqrt(n); i++) {
		if (n % i == 0) {
			int l = dfs(n / i, i + 1, 1);
			if (l > maxl) {
				maxl = l;
				res = i;
			}
		}
	}
	printf("%d\n", maxl);
	for (int i = 0; i < maxl - 1; i++) {
		printf("%d*", res + i);
	}
	printf("%d\n", res + maxl - 1);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq1013459920/article/details/85041863