PAT甲级——1096 Consecutive Factors (数学题)

该博客介绍了PAT甲级编程竞赛中的一道数学题——1096 Consecutive Factors。题目要求找到正整数N的所有因子中,存在最长的连续因子序列,并输出序列长度及最小序列。解决方案是通过遍历2到sqrt(N)+1,找出能整除N的连续乘积,存储连续数字并比较序列大小,最终输出序列长度和序列本身。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1096 Consecutive Factors (20 分)

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<2​31​​).

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

题目大意:一个数字可以写成若干因子相乘的形式,在这些因子中寻找连续的数字形成一个序列,使得此序列的成员个数最多,输出成员个数最多且数值最小的序列,写成相乘的格式。

思路:直接从2遍历到sqrt( N ) +1,找能整除N的连续乘积,此乘积的连续数字存入tmpAns数组中,size最大的那组序列就是答案。

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int N, x;
vector <int> ans, tmpAns;
int main()
{
	int i, product = 1;
	scanf("%d", &N);
	x = sqrt(N) + 1;
	/*寻找最多的连续的数字,连续相乘的积能整除N*/
	for (i = 2; i <= x; i++) {
		product *= i;
		tmpAns.push_back(i);
		if (product <= N && N % product == 0 && tmpAns.size() > ans.size())//乘积小于N且能整除N又是目前找到的最多连续数字
			ans = tmpAns;
		else if(product > N || N % product != 0) {//乘积大于N或者新加入的i使得乘积无法整除N
			tmpAns.clear();
			if (N % i != 0)//新加入的i不能整除N,将product初始化
				product = 1;
			else {//新加入的i是N的因子,意味着product的值超过了N,那么从前面开始删除节点,使得product小于N
				int tmpPro = product, j;
				for (j = 2; j <= i; j++) {
					tmpPro = tmpPro / j;
					if (tmpPro <= N && N % tmpPro == 0) {
						product = tmpPro;
						break;
					}
				}
				for (j++; j <= i; j++)
					tmpAns.push_back(j);
			}
		}
	}
	/*N为素数的时候输出它本身*/
	if (ans.size() == 0)
		printf("1\n%d\n", N);
	else {
		printf("%d\n", ans.size());
		for (int i = 0; i < ans.size(); i++) {
			if (i != 0)
				printf("*");
			printf("%d", ans[i]);
		}
	}
	return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值