【PAT】A1096. Consecutive Factors (20)

Author: CHEN, Yue

Organization: 浙江大学

Time Limit: 400 ms

Memory Limit: 64 MB

Code Size Limit: 16 KB

A1096. 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<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

Code

//NKW 甲级真题1007
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
using namespace std;
vector<int> vi, vt;
int main(){
	int n, cnt, rcnt = -1, num;
	scanf("%d", &n);
	for (int i = 2; i <= sqrt(n); i++){    //连乘的第一个数
		cnt = 0;
		num = n;
		vt.clear();
		for (int j = i; j <= n; j++){
        //这里如果写成j<=sqrt(n)也能通过,但是其实有问题,如输入6 输出为1\n2,因为3>sqrt(6)
			if (num%j == 0){
				num /= j;
				vt.push_back(j);
				cnt++;
			}
			if (j - i + 1 != cnt)	break;
		}
		if (cnt > rcnt){
			rcnt = cnt;
			vi.clear();
			vi = vt;
		}
	}
	if (vi.size()){
		printf("%d\n", vi.size());
		for (int i = 0; i < vi.size(); i++){
			if (i)	printf("*");
			printf("%d", vi[i]);
		}
	}
	else	printf("1\n%d", n);
	printf("\n");
	return 0;
}

程序分析:

-寻找最长连续因子的个数。

-本题使用暴力法求解,没有用什么算法所以对循环的条件需要抠一抠。最暴力的解法的写法是本程序12行和16行写成:

12    i<=n

16    j<=n

但是这样超时了。

所以经过思考,对于12行可以改为i<=sqrt(n),这是因为,i是我们连乘的第一个数,本题要求在连乘长度相同时首位取最小。如果i>sqrt(n),那么这个情况下连乘的长度为1(显然此时i=n)。显然Len(i>sqrt(n))<=Len(i<=sqrt(n)),故我们只需要考虑i<=sqrt(n)的情况即可。

而对于16行,最初我想当然的也改为了j<=sqrt(n),在NKW和PTA上也都通过了,但是我无聊试了一下6和20,突然发现结果是:1\n2和1\n4   (这是我偷懒的写法,相信大家都懂是什么意思)

这显然不对,正确的结果应该是2\n2*3和2\n4*5。我还发现《算法笔记——上级实战训练》(2018年1月第一版P219)上有这样一句话:

我想了想,3>sqrt(6)=2.44,6可以被3整除。这~~~~~

所以在我写的这个程序里,还是使用j<=n,当然啦,我这样写能够通过。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值