A. k-Factorization
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard outputGiven 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
水题:可以想到只要从最小数开始判断因数,一旦是该数的因数就记入结果数组,同时更新该数,当已经统计到结果数组的因数个数达到k-1个时,直接将最后的数记入结果数组即可,这里需要判断一下,因为最后一个结果因数不可为1.
代码如下:
//
// main.cpp
// A. k-Factorization
//
// Created by 徐智豪 on 2017/4/15.
// Copyright © 2017年 徐智豪. All rights reserved.
//
#include <iostream>
using namespace std;
int k,n;int tcount=1;
int flag=1;
int ans[1000];
void print()
{
tcount=1;
int temp=k;
if(n==1)
{
ans[tcount]=k;
return ;
}
int i;
for( i=2;i<=k;i++)
{
while(temp%i==0)
{
ans[tcount++]=i;
temp/=i;
if(tcount==n&&temp>1)
{
ans[tcount]=temp;
return ;
}
else if(tcount==n&&temp==1)
{
flag=0;
}
}
}
if(i==k+1)
{
flag=0;
return ;
}
}
int main(int argc, const char * argv[]) {
cin>>k>>n;
print();
if(flag)
{
for(int i=1;i<tcount;i++)
{
cout<<ans[i]<<" ";
}
cout<<ans[tcount]<<endl;
}
else cout<<-1<<endl;
return 0;
}
本文探讨了k-Factorization问题,即给定一个正整数n,寻找k个严格大于1的整数,使它们的乘积等于n。文章提供了具体的解决方法,并通过示例演示了解决方案的有效性。
815

被折叠的 条评论
为什么被折叠?



