Trong bài toán này, chúng ta được cho một số n. Nhiệm vụ là in tất cả các tổ hợp thừa số của n.
Ví dụ để hiểu rõ hơn:
Đầu vào: 24 → Đầu ra: 2 2 2 3, 2 4 3 8, 3 4 6, 2 12
Ta sử dụng hàm đệ quy để tìm tổ hợp thừa số của số. Lưu tất cả tổ hợp vào mảng các mảng.
Ví Dụ
Mã minh họa giải pháp:
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>> factor_Combo;
void genreateFactorCombinations(int first, int eachFactor, int n, vector<int> factor) {
if (first > n || eachFactor > n)
return;
if (eachFactor == n) {
factor_Combo.push_back(factor);
return;
}
for (int i = first; i < n; i++) {
if (i * eachFactor > n)
break;
if (n % i == 0) {
factor.push_back(i);
genreateFactorCombinations(i, i * eachFactor, n, factor);
factor.pop_back();
}
}
}
void printcombination() {
for (int i = 0; i < factor_Combo.size(); i++) {
for (int j = 0; j < factor_Combo[i].size(); j++)
cout << factor_Combo[i][j] << "\t";
cout << endl;
}
}
int main() {
int n = 24;
vector<int> single_result_list;
cout << "Tất cả tổ hợp thừa số của " << n << " là:\n";
genreateFactorCombinations(2, 1, n, single_result_list);
printcombination();
return 0;
}
Đầu Ra
Tất cả tổ hợp thừa số của 24 là: 2 2 2 3 2 2 6 2 3 4 2 12 3 8 4 6