Find if n can be written as product of k numbers

Given a positive number n, we need to print exactly k positive numbers (all greater than 1) such that product of those k numbers is n. If there doesn’t exist such k numbers, print -1 . If there are many possible answer you have to print one of that answer where k numbers are sorted.


Input : n = 54, k = 3
Output : 2, 3, 9
Note that 2, 3 and 9 are k numbers
with product equals to n.

Input : n = 54, k = 8
Output : -1

This problem uses idea very similar to print all prime factors of a given number.
The idea is very simple. First we calculate all prime factors of n and store them in a vector. Note we store each prime number as many times as it appears in it’s prime factorization. Now to find k numbers greater than 1, we check if size of our vector is greater then or equal to k or not.

  1. If size is less than k we print -1.
  2. Else we print first k-1 factors as it is from vector and last factor is product of all the remaining elements of vector.

Note we inserted all the prime factors in sorted manner hence all our number in vector are sorted. This also satisfy our sorted condition for k numbers.

// C++ program to find if it is possible to
// write a number n as product of exactly k
// positive numbers greater than 1.
#include <bits/stdc++.h>
using namespace std;

// Prints k factors of n if n can be written
// as multiple of k numbers.  Else prints -1.
void kFactors(int n, int k)
    // A vector to store all prime factors of n
    vector<int> P;

    // Insert all 2's in vector
    while (n%2 == 0)
        n /= 2;

    // n must be odd at this point
    // So we skip one element (i = i + 2)
    for (int i=3; i*i<=n; i=i+2)
        while (n%i == 0)
            n = n/i;

    // This is to handle when n > 2 and
    // n is prime
    if (n > 2)

    // If size(P) < k, k factors are not possible
    if (P.size() < k)
        cout << "-1" << endl;

    // printing first k-1 factors
    for (int i=0; i<k-1; i++)
        cout << P[i] << ", ";

    // calculating and printing product of rest
    // of numbers
    int product = 1;
    for (int i=k-1; i<P.size(); i++)
        product = product*P[i];
    cout << product << endl;

// Driver program to test above function
int main()
    int n = 54, k = 3;
    kFactors(n, k);
    return 0;


2, 3, 9

This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Writing code in comment? Please use, generate link and share the link here.