PAT--1096 Consecutive Factors--水题

题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805370650738688

题目大意

输出n的最长连续的因子。

分析

看似n的范围很大(2^31),但是仔细想一下只要遍历到根号n就可以了。举个例子,假设n等于64,那么根号n就是8,也就是说,8*8=64,如果遍历到一个比8还大的数,例如10,10的下一个数是11,很显然10*11大于64,所以根号n后面的数最多只有一个连续的因子,而题目又说当长度等于0时,输出n本身,其实就相当于一个因子,那么根号n后面的数我们就不用管了。

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
ll n;
int cnt, ans[1100];
int main() {
	cnt = 0;
	scanf("%lld", &n);
	for(int i = 2; i <= sqrt(n); i++) {
		ll m = n;
		int j = i;
		while(m % j == 0) {
			m /= j;
			j++;
		}
		j--;
		if(j - i + 1 > cnt) {
			cnt = j - i + 1;
			int d = 0;
			for(int k = i; k <= j; k++)
				ans[d++] = k;
		}
	}
	if(cnt == 0) {
		printf("1\n");
		printf("%lld\n", n);
	} else {
		printf("%d\n", cnt);
		for(int i = 0; i < cnt; i++)
			printf("%d%s", ans[i], i == cnt - 1 ? "\n" : "*");
	}
	return 0;
}
发布了150 篇原创文章 · 获赞 4 · 访问量 6959

猜你喜欢

转载自blog.csdn.net/Napom/article/details/102864683