Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

พิมพ์ชุดตัวประกอบทั้งหมดของตัวเลขใน C++

ภาพรวมปัญหา

ได้รับตัวเลข n ต้องพิมพ์ชุดตัวประกอบ (factor combinations) ทั้งหมดของ n

ตัวอย่าง

Input: 24
Output:
2 2 2 3
2 2 6
2 3 4
2 12
3 8
4 6

วิธีแก้ปัญหา (Recursion)

ใช้ฟังก์ชันเวียนเกิดหาชุดตัวประกอบ เริ่มจากตัวประกอบ 2 ขึ้นไป เก็บชุดที่ผลคูณเท่ากับ n

ตัวอย่างโค้ด C++

#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;
}

ผลลัพธ์ (Output)

All Factor combinations of 24 are:
2 2 2 3
2 2 6
2 3 4
2 12
3 8
4 6