更多PAT题解尽在我的个人博客---我的个人bok
题目
题目翻译
题目描述
原文
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.
翻译
在正数N的所有因数中,可能存在一些连续的数字。举个例子,630 可以 被3*5*6*7
组成,这里的5*6*7
是三个连续的数字。现在给定任意一个正数N,你应该找出最大的连续因子数量,并且列出最小的连续因子序列。
题目解析
很简单,直接暴力:
解题思路:外层遍历起点,里层遍历连续的因子,最后取最长的结果即可。
代码拆解
- Input()函数输入和更新
void Input() { ios::sync_with_stdio(false); cin >> N; int cmp = sqrt(N); for (int i = 2; i <= cmp; i++) { int t = N, start = i; while (t % start == 0) { //一旦出现不连续的情况直接跳出循环 t /= start; start++; } if (start - i > mxLen) {//开始更新 mxLen = start - i; first = i; } } }
- print函数输出结果
void print() { if (mxLen) { //一旦能分解成多个就这样打印,否则就是没有更新,则输出1 cout << mxLen << endl; cout << first; for (int i = 1; i < mxLen; i++) { cout << '*' << first + i; } } else { cout << 1 << endl; cout << N; } }
整合代码得出答案
效率还行
#include<bits/stdc++.h> using namespace std; int N, first, mxLen; //数字,起点,最大的长度 //解题思路:外层遍历起点,里层遍历连续的因子,最后取最长的结果即可。 void Input() { ios::sync_with_stdio(false); cin >> N; int cmp = sqrt(N); for (int i = 2; i <= cmp; i++) { int t = N, start = i; while (t % start == 0) { //一旦出现不连续的情况直接跳出循环 t /= start; start++; } if (start - i > mxLen) { mxLen = start - i; first = i; } } } void print() { if (mxLen) { //一旦能分解成多个就这样打印,否则就是没有更新,则输出1 cout << mxLen << endl; cout << first; for (int i = 1; i < mxLen; i++) { cout << '*' << first + i; } } else { cout << 1 << endl; cout << N; } } int main() { Input(); print(); return 0; }