A. k-Factorization
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Given a positive integer n, find k integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to n.
Input
The first line contains two integers n and k (2 ≤ n ≤ 100000, 1 ≤ k ≤ 20).
Output
If it’s impossible to find the representation of n as a product of k numbers, print -1.
Otherwise, print k integers in any order. Their product must be equal to n. If there are multiple answers, print any of them.
Examples
input
100000 2
output
2 50000
input
100000 20
output
-1
input
1024 5
output
2 64 2 2 2
题意:给你两个数,n,k,问你n能不能变成k个大于1的数的乘积,如果能,输出这k个数,如果不能,输出-1.
解题思路:利用素数唯一分解定理搞一下就行。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
int n,k;
int res;
bool prime[maxn];
int ans[maxn];
int result[maxn];
void init()
{
//素数筛选
memset(prime,true,sizeof(prime));
res = 0;
for(int i = 2; i <= maxn; i++)
{
if(prime[i])
{
res++;
ans[res] = i;
}
for(int j = 1; i*ans[j] <= maxn&&j <= res; j++)
{
prime[i*ans[j]] = false;
if(i%ans[j] == 0) break;
}
}
}
int main()
{
scanf("%d%d",&n,&k);
init();
int len = 0;
int loc = 1;
if(k == 1)
{
printf("%d\n",n);
return 0;
}
while(true)
{
if(n%ans[loc] == 0)
{
len++;
result[len] = ans[loc];
n /= ans[loc];
}
else loc++;
if(n == 1) break;
if(len == k - 1)
{
len++;
result[len] = n;
break;
}
}
if(len == k)
{
printf("%d",result[1]);
for(int i = 2; i <= k; i++)
{
printf(" %d",result[i]);
}
printf("\n");
}
else printf("-1\n");
return 0;
}