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

C++Server Side ProgrammingProgramming

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.

Example

#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
   int getKFactors(int n, int k){
   int i;
   vector<int> vec;
   while(n % 2 == 0){
      vec.push_back(2);
      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;
         vec.push_back(i);
      }
   }
   if(n > 2){
      vec.push_back(n);
   }
   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);
}

Output

2, 3, 9
raja
Published on 01-Nov-2019 14:27:45
Advertisements