Find if n can be written as product of k numbers in C++

Suppose we have a number N. We have another number k. We have to check the number can be represented using k numbers or not. Suppose a number 54, and k = 3, then it will print the numbers like [2, 3, 9], if it cannot be represented, then print that.

To solve this, we will find all prime factors of N, and store them into a vector, then to find k numbers greater than 1, we check the size of the vector is greater than k or not. If size is less than k, then return -1, otherwise print first k-1 factors and the last factor will be the product of all remaining numbers.


using namespace std;
   int getKFactors(int n, int k){
   int i;
   vector<int> vec;
   while(n % 2 == 0){
      n = n/2; //reduce n by dividing this by 2
   for(i = 3; i <= sqrt(n); i=i+2){ //i will increase by 2, to get only odd numbers
      while(n % i == 0){
         n = n/i;
   if(n > 2){
   if(vec.size() < k){
      cout << "Cannot be represented";
         return -1;
   for (int i=0; i<k-1; i++)
   cout << vec[i] << ", ";
   int prod = 1;
   for (int i=k-1; i<vec.size(); i++)
   prod = prod*vec[i];
   cout << prod << endl;
int main() {
   int n = 54, k = 3;
   getKFactors(n, k);


2, 3, 9

Updated on: 01-Nov-2019


Kickstart Your Career

Get certified by completing the course

Get Started