fork download
  1.  
  2. // C++ program to find if it is possible to
  3. // write a number n as product of exactly k
  4. // positive numbers greater than 1.
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7.  
  8. // Prints k factors of n if n can be written
  9. // as multiple of k numbers. Else prints -1.
  10. void kFactors(int n, int k)
  11. {
  12. // A vector to store all prime factors of n
  13. vector<int> P;
  14.  
  15. // Insert all 2's in vector
  16. while (n%2 == 0)
  17. {
  18. P.push_back(2);
  19. n /= 2;
  20. }
  21.  
  22. // n must be odd at this point
  23. // So we skip one element (i = i + 2)
  24. for (int i=3; i*i<=n; i=i+2)
  25. {
  26. while (n%i == 0)
  27. {
  28. n = n/i;
  29. P.push_back(i);
  30. }
  31. }
  32.  
  33. // This is to handle when n > 2 and
  34. // n is prime
  35. if (n > 2)
  36. P.push_back(n);
  37.  
  38. // If size(P) < k, k factors are not possible
  39. if (P.size() < k)
  40. {
  41. cout << "-1" << endl;
  42. return;
  43. }
  44.  
  45. // printing first k-1 factors
  46. for (int i=0; i<k-1; i++)
  47. cout << P[i] << ", ";
  48.  
  49. // calculating and printing product of rest
  50. // of numbers
  51. int product = 1;
  52. for (int i=k-1; i<P.size(); i++)
  53. product = product*P[i];
  54. cout << product << endl;
  55. }
  56.  
  57. // Driver program to test above function
  58. int main()
  59. {
  60. int n = 54, k = 3;
  61. kFactors(n, k);
  62. return 0;
  63. }
Success #stdin #stdout 0s 4448KB
stdin
Standard input is empty
stdout
2, 3, 9