PAT甲级--Consecutive Factors


题目


OJ平台

题目翻译

题目描述

原文
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,你应该找出最大的连续因子数量,并且列出最小的连续因子序列。

题目解析

很简单,直接暴力:
解题思路:外层遍历起点,里层遍历连续的因子,最后取最长的结果即可。

代码拆解

  1. 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;
    }
  }
}
  1. 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值