1096 Consecutive Factors

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

题意:

给出一个正整数,找出其最长连续因子,若长度相等,则输出数值小的。

思路:

因为是要输出连续的因子,所以最大值不会超过sqrt(N)+1,知道了这一点之后然后便利寻找就行了。

注意:初始化len的时候应将其初始化为0.

Code:

#include<iostream>
#include<cmath>

using namespace std;

int main() {
    long N;
    cin >> N;

    int maxn = sqrt(N) + 1;
    long temp = 1, len = 0;
    int startPos = 0;

    for (int i = 2; i <= maxn; ++i) {
        int j;
        for (j = i; j <= maxn; ++j) {
            temp *= j;
            if (N % temp != 0) break;
        }
        if (j - i > len) {
            len = j - i;
            startPos = i;
        }
        temp = 1;
    }

    if (len == 0) cout << 1 << endl << N;
    else {
        cout << len << endl;
        for (int i = 0; i < len; ++i) {
            cout << startPos + i;
            if (i != len-1) cout << '*';
        }
    }

    return 0;
}

  

参考:

https://www.liuchuo.net/archives/2110

永远渴望,大智若愚(stay hungry, stay foolish)
原文地址:https://www.cnblogs.com/h-hkai/p/12612818.html