[PAT-A 1096]Consecutive Factors

在这里插入图片描述
题目大意:
给出一个正整数N,求一段连续的整数,使得N能被这段连续的整数的乘积整除。如果有多个方案,输出连续整数个数最多的方案。

思路:
1)N不会被除自己以外的大于根号N数整除,因此只需要从2-根号N遍历连续整数的第一个,求此时N能被最多多少个连续整数的乘积整除。
在此过程中,如果发现有长度比当前最长长度ansLen更长的情况,更新ansLen和第一个整数ansI.
ansLen,ansI初值为0。
2)如果遍历结束之后ansLen仍然为0,那么说明答案就是N本身,否则,输出从ansI开始的连续ansLen个数。

AC代码:

//PAT_A 1096
#include<cstdio>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
int main() {
	ll n, ansI = 0, ansLen = 0;
	(void)scanf("%lld", &n);
	ll sqr = (ll)sqrt((1.0) * n);
	for (ll i = 2; i <= sqr; i++) {
		ll temp = 1, j = i;
		while (true) {
			temp *= j;
			if (n % temp != 0)break;
			if (j - i + 1 > ansLen) {
				ansLen = j - i + 1;
				ansI = i;
			}
			j++;
		}
	}
	if (ansLen == 0)printf("1\n%lld\n", n);
	else {
		printf("%lld\n", ansLen);
		for (ll i = 0; i < ansLen; i++) {
			printf("%lld", ansI + i);
			if (i < ansLen - 1)printf("*");
		}
	}
	return 0;
}
发布了142 篇原创文章 · 获赞 1 · 访问量 4575

猜你喜欢

转载自blog.csdn.net/weixin_44699689/article/details/104283516