pat 1096

1096. Consecutive Factors (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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<231).

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

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;

int main(void)
{
	int value;
	scanf("%d", &value);
	int maxNums = 0, startIndex;
	// 上界的确定
	int upMax = sqrt(value * 1.0) + 1;
	/*int i, j = 2, currentValue;
	while (j < upMax)
	{
		currentValue = value;*/
		/*
			策略:计算以j为起始元素的连续因素,用currentValue依序除以j, j+1, j+2……直到结果不能整除,
			假设增至为i时不能整除,则循环再次以j = i + 1位起始元素计算连续因素,直到j = upMax,则不再有连续因素
			特殊情况考虑:如果value是一个素数,则从[2, upMax)之间不会存在连续因素,则最后结果的连续因素就是value
			所以初始化时,maxNums = 0,遇到更长的连续因素时则会更新startIndex, 不存在更长的连续因素,则不会更新,如果maxNums == 0, 则为素数
			
			上述策略存在bug,举例4 * 5  * 6 * 7 * 8 = 6720; 2 * 3 * 4 * 5 * 7 * 8 = 6720;
			如按上述策略执行则会求出2*3*4*5,而实际答案应该是4 * 5  * 6 * 7 * 8,所有需要重新改进上述策略
		*/
		/*i = j;
		while (currentValue % i == 0)
		{
			currentValue /= i;
			++i;
		}
		if (i - j > maxNums)
		{
			maxNums = i - j;
			startIndex = j;
		}
		j = i + 1;
	}*/
	/*
		上述方法的改进:以i指向连续因素的第一个元素,j指向连续因素的下一个元素,如果currentValue % j == 0,则++j, 否则++i
		特殊情况考虑,当没有连续元素,即i == j时,currentValue % j != 0, 则i, j同时加1
	*/
	int i = 2, j = 2, currentValue = value;
	while (i < upMax)
	{
			while (currentValue % j == 0)
			{
				currentValue /= j;
				++j;
			}
			if (i == j)
			{
				++i;
				++j;
			}
			else
			{
				if (j - i > maxNums)
				{
					maxNums = j - i;
					startIndex = i;
				}
				currentValue *= i;
				++i;
			}
	}
	if (maxNums == 0)
		printf("1\n%d\n", value);
	else
	{
		printf("%d\n", maxNums);
		printf("%d", startIndex);
		++startIndex;
		for (int i = 1; i < maxNums; ++i)
			printf("*%d", startIndex++);
		printf("\n");
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值