PTA brushing record: L1-006 continuous factor (20 points)

L1-006 Continuous factor (20 points)

Title description:
There may be several consecutive numbers in a factor of a positive integer N. For example, 630 can be decomposed into 3×5×6×7, where 5, 6, and 7 are 3 consecutive numbers. Given any positive integer N, it is required to write a program to find the number of the longest continuous factor and output the smallest continuous factor sequence.

Input format:
Input a positive integer N in one line (1<N<2**31).

Output format:
first output the number of the longest continuous factor in the first row; then output the smallest continuous factor sequence in the format of factor 1 factor 2 ... * factor k in the second row , where the factors are output in increasing order, 1 Not counted.

Input sample:
630
Output sample:
3
5 6 7

Problem-solving idea:
For a number N, all its factors must be within sqrt(N), so use brute force traversal until sqrt(N). Enumerate the factor of each time as the starting point, then find the number of continuous factors, compare with the previous number of continuous factors, take the maximum value, and count the number of factors as the starting point.
Finally output the number of consecutive factors, and traverse all the factors from the starting point to output.

Note:
1) The final output should be judged. When the input number is prime or 0, just output this number directly. Of course, the factor number at this time is 1.

Customs clearance code:

#include <iostream>
#include <string>

using namespace std;

typedef long long ll;

int main() {
    
    
	ll num, start, res = 0;

	cin >> num;

	for (ll i = 2; i * i < num + 1; i++) {
    
    
		if (num % i != 0) continue;

		ll temp = num;
		ll len = 0;
		for (ll j = i; temp % j == 0; j++) {
    
    
			temp /= j;
			len++;
		}

		if (len > res) {
    
    
			res = len;
			start = i;
		}
	}
	
	if (res == 0) {
    
    
		cout << '1' << endl << num;
	} else {
    
    
		cout << res << endl;
		bool isFirst = true;
		for (int i = 0; i < res; i++) {
    
    
			if (isFirst) {
    
    
				cout << start + i;
				isFirst = !isFirst;
			} else {
    
    
				cout << '*' << start + i;
			}
		}
	}
	
	return 0;
}

Customs clearance screenshot:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45711556/article/details/109371376