1. 程式人生 > >浙大pat | 浙大pat 牛客網甲級 1007 Consecutive Factors (20) 數論

浙大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 (1<n<231).</n<2

輸出描述:

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 <iostream>
#include <math.h>
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<<endl;
		cout << N;
	}
	else
	{
		cout << theMaxLength << endl;
		for (int i = theMaxNum; i <= theMaxNum + theMaxLength - 1; i++)
		{
			cout << i;
			if (i != theMaxNum + theMaxLength - 1) cout << "*";
		}
	}
    
	return 0;
}