题解 CF797A 【k-Factorization】

这题真是细节多。但是算法很好掌握。

对于n\large n,将其分解质因数,可以得到:

n=p1p2p3pn\Large n = p_1 * p_2 * p_3 …… * p_n

如果其质因数个数小于k,无解。

如果其质因数个数等于k,全部输出。

如果其质因数个数大于k,前k - 1个全部输出,剩下的乘起来输出。

代码:

#include <iostream>
using namespace std;

int a[10005];

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
	int n, k, cur = 0;
	cin >> n >> k;
	int x = n; 
	for(register int i = 2; i <= x - 1; i++)
	{
		while(n % i == 0)
		{
			a[++cur] = i;
			n /= i;
		}
	}
	if(cur == 0) //若n为质数,cur为0,要把n存回去
	{
		cur = 1;
		a[1] = n;
	}
	if(cur < k) {cout << "-1\n"; return 0;}
	else if(cur == k) for(register int i = 1; i <= k; i++) cout << a[i] << " ";
	else
	{
		for(register int i = 1; i <= k - 1; i++) cout << a[i] << " ";
		int mul = 1;
		for(register int i = k; i <= cur; i++) mul *= a[i];
		cout << mul << endl;
	}
	return 0;	
}
posted @ 2020-12-19 11:01  HappyBobb  阅读(11)  评论(0)    收藏  举报  来源