浙大pat | 浙大pat 牛客网甲级 1007 Consecutive Factors (20) 数论

题目描述

Among all the factors of a positive integer N, there may existseveral consecutive numbers.  Forexample, 630 can be factored as 3*5*6*7, where 5, 6, and 7 are the threeconsecutive numbers.  Now given anypositive N, you are supposed to find the maximum number of consecutive factors,and list the smallest sequence of the consecutive factors.



输入描述:

Each input file contains one test case, which gives the integerN (131).




输出描述:

For each test case, print in the first line the maximum numberof consecutive factors.  Then in thesecond line, print the smallest sequence of the consecutive factors in theformat "factor[1]*factor[2]*...*factor[k]", where the factors arelisted in increasing order, and 1 is NOT included.



输入例子:

630



输出例子:

3

5*6*7

这一题让你找到一系列的数,要求这些数里面有一个最长的连续子序列

对于N而言

1)       假如N是质数,那么最长序列就是它本身

2)       假如N是合数,但是没有连续相乘可以得到他自己的数,那么答案就是最大的因子

经过分析可以发现,连续因子序列不可能含有大于sqrt(N)的数,因此只需要遍历到sqrt(N)就好了,更进一步发现,连续因子每一个都要是N的因子,且这些连续因子相乘也要是N的因子,因此从2到sqrt(N)遍历一遍,观察最长的连续因子相乘的结果也是N的因子的序列就是所求,假如这个序列的长度为1,那么说明N是合数,但是没有连续相乘可以得到他自己的数,假如这个序列的长度为0,那么说明N是质数,直接输出他本身就好了

#include 
#include 
using namespace std;

int theMaxNum, theMaxLength=0;

int main()
{
	int N;
	int left, right;
	int theResultTmp = 1;
	cin >> N;

	left = right = 2;
	for (right = 2; right <= sqrt(N);)
	{
		if (N%right == 0)
		{
			theResultTmp *= right;
			right++;
			if (N % theResultTmp !=0) { theResultTmp = 1; left++; right = left; continue; }
			else {
				  if (right - left > theMaxLength)
				  {
					theMaxNum = left;
					theMaxLength = right - left;
					continue;
				  }
			}
		}
		else
		{
			theResultTmp = 1;
			right++;
			left = right;
		}
	}
	if (theMaxLength == 0)
	{
		cout << 1<

你可能感兴趣的:(浙大pat)