PTA A1096 Consecutive Factors(20分)

题目:click me~

题意:给出整数N,需要找到连续因子的最大个数,若有多个,输出第一个数最小的那个序列。

解题思路:

步骤一:首先注意到,N不会被除自己外的大于sqrt(N)的整数整除,因此只需要从2~sqrt(N)遍历连续整数的第一个,求此时N能被最多多少个连续整数的乘积整除。在此过程中,如果发现长度比当前最长长度anslen更长的情况(anslen初始化为0),就更新anslen和对应第一个整数ansi。

步骤二:若遍历结束后anslen还是等于0,那么说明答案就是N本身;否则,输出[ansi,ansi+anslen)区间内的整数。

code

#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
typedef long long LL;
int main() {
	LL n;
	cin >> n;
	LL sqr = (LL)sqrt(1.0*n);
	LL ansi=0, anslen=0;//anslen为最长连续整数个数,ansi为对应的第一个整数
	for (LL i = 2;i <= sqr;i++) {
		LL temp = 1, j = i;//temp为当前连续整数的乘积
		while (1) {
			temp *= j;
			if (n%temp != 0)break;//若不能整除,则结束计算
			if (j - i + 1 > anslen) {//发现了更长的长度
				ansi = i;//更新
				anslen = j - i + 1;
			}
			j++;//下一个整数
		}
	}
	if (anslen == 0)cout << "1" << endl << n;
	else {
		cout << anslen << endl;
		for (int i = 0;i < anslen;i++) {
			if (i != 0)cout << "*";
			cout << ansi + i;
		}
	}
	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值