fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <set>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. // 獲取一個數的所有質因數
  9. void primeFactors(int n, vector<int>& factors) {
  10. for (int i = 2; i * i <= n; ++i) {
  11. while (n % i == 0) {
  12. factors.push_back(i);
  13. n /= i;
  14. }
  15. }
  16. if (n > 1) {
  17. factors.push_back(n);
  18. }
  19. }
  20.  
  21. // 遞迴生成所有可能的分解組合
  22. void generateCombinations(const vector<int>& factors, vector<int>& current, int index, int product, int target, set<vector<int>>& results) {
  23. if (product == target) {
  24. vector<int> temp = current;
  25. sort(temp.begin(), temp.end()); // 排序以避免重複
  26. results.insert(temp);
  27. return;
  28. }
  29. if (product > target || index >= factors.size()) {
  30. return;
  31. }
  32. // 不選擇當前因數
  33. generateCombinations(factors, current, index + 1, product, target, results);
  34.  
  35. // 選擇當前因數
  36. current.push_back(factors[index]);
  37. generateCombinations(factors, current, index, product * factors[index], target, results);
  38. current.pop_back();
  39. }
  40.  
  41. vector<vector<int>> factorCombinations(int n) {
  42. vector<int> factors;
  43. primeFactors(n, factors);
  44. set<vector<int>> results;
  45. vector<int> current;
  46. generateCombinations(factors, current, 0, 1, n, results);
  47. return vector<vector<int>>(results.begin(), results.end());
  48. }
  49.  
  50. int main() {
  51. int n = 12; // 你可以在這裡更改數字
  52. vector<vector<int>> combinations = factorCombinations(n);
  53.  
  54. cout << n << " 的所有分解方式為:" << endl;
  55. for (const auto& combination : combinations) {
  56. for (int num : combination) {
  57. cout << num << " ";
  58. }
  59. cout << endl;
  60. }
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
12 的所有分解方式為:
2 2 3