列印 C++ 中因⼦的所有組合
在該問題中,我們得到一個數 n。我們的任務是打印出 n 的所有組合因子。
我們舉個例子來更好地理解這個主題——
Input: 24 Output: 2 2 2 3 2 4 3 8 3 4 6 2 12
為此,我們將使用遞迴函式,該函式將找到該數的因子組合。而且,我們將把所有組合儲存在一個數組的陣列中。
例子
此程式碼將顯示我們解決方案的實現。
#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<<"All Factor combinations of "<<n<<" are :\n";
genreateFactorCombinations(2, 1, n, single_result_list);
printcombination();
return 0;
}輸出
All Factor combinations of 24 are − 2 2 2 3 2 2 6 2 3 4 2 12 3 8 4 6
廣告
資料結構
網路
關係資料庫管理系統
操作系
Java
iOS
HTML
CSS
安卓
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP