A. k-Factorization

来源:互联网 发布:农村淘宝服务站利润 编辑:程序博客网 时间:2024/05/22 11:53

http://codeforces.com/problemset/problem/797/A

A. k-Factorization
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Given a positive integer n, find k integers (not necessary distinct) such that all these integers are strictly greater than1, and their product is equal to n.

Input

The first line contains two integers n andk (2 ≤ n ≤ 100000,1 ≤ k ≤ 20).

Output

If it's impossible to find the representation of n as a product ofk numbers, print -1.

Otherwise, print k integers in any order. Their product must be equal ton. 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的数的乘积是n,若不存在输出-1

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
int ans[100005];
int a[100005];
int main()
{

    a[1]=0;
    a[2]=1;
    a[3]=1;
    for(int i=2;i<=100005;i++)
    a[i]=1;
    for(int i=2;i<=100005;i++)
    {
        if(a[i]==1)
        {
            for(int j=2*i;j<=100005;j+=i)
                a[j]=0;
        }
    }
    int n,k;
    while(~scanf("%d%d",&n,&k))
    {
      if(k==1)printf("%d\n",n);
      else
      {
        int nn=n;
        int flog=0; int r=1;
        for(int len=2;len<=nn;len++)
        {

         if(a[len]==1&&n%len==0)
           {
               ans[r]=len;
               n=n/len;
               len--; r++;
           }
            if(n==1)
           {
                printf("-1\n");
                flog=1;
                break;
           }
           if(r==k)
           {
               ans[r]=n;
               break;
           }
       }
       if(flog==0)
        for(int i=1;i<=r;i++)
        {
        if(i==r)
            printf("%d\n",ans[i]);
        else
           printf("%d ",ans[i]);
        }
      }
    }
}



0 0
原创粉丝点击