PAT A1096 Consecutive Factors (20point(s))

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
  • 思路: 数据范围:(1, 231),在int范围内
    常识:一个数不可能被两个比他sqrt大的数整除,比如16(sqr = 4)不可能等于4*5,即一个数至多有一个比sqr大的因子或没有

枚举2开始到sqr作为Consecutive Factors的起始,看Consecutive Factors能增长到多少,并更新最大长度(及其对应的起始位置)

  • code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
	int n;
	scanf("%d", &n);
	int sqr = sqrt(1.0 * n), max_len = 0, start = 2;
	for(int i = 2; i <= sqr; ++i){
		int tmp = n, j = i;
		while(tmp % j == 0){
			tmp /= j;
			j++;
		}
		if(j - i > max_len){
			max_len = j - i;
			start = i;
		}	
	}
	if(max_len == 0){
		printf("1\n%d", n);
	}else{
		printf("%d\n", max_len);
		for(int i = start; i < start + max_len; ++i){
			if(i == start) printf("%d", i);
			else printf("*%d", i);
		}
	}
	return 0;
} 
发布了271 篇原创文章 · 获赞 5 · 访问量 6516

猜你喜欢

转载自blog.csdn.net/qq_42347617/article/details/104191781