How to print all possible ways to write a number (N) as a sum of two or more positive integers in C++

1 Answer

0 votes
#include <iostream>
#include <vector>

void print_vector(std::vector<int>& vec) {
    if (vec.size() != 1) {
        for (int i = 0; i < vec.size(); i++) {
            if (i < vec.size() - 1) {
                std::cout << vec[i] << " + ";
            } else {
                std::cout << vec[i];
            }
        }
    }
    
    std::cout << "\n";
}

void all_ways_to_write_a_number_as_sum_of_two_or_more_ints(std::vector<int>& vec, int i, int n) {
    if (n == 0) {
        print_vector(vec);
    }

    for (int j = i; j <= n; j++) {
        vec.push_back(j);
 
        all_ways_to_write_a_number_as_sum_of_two_or_more_ints(vec, j, n - j);

        vec.pop_back();
    }
}
 
int main()
{
    int n = 5; // The number
 
    std::vector<int> arr;

    all_ways_to_write_a_number_as_sum_of_two_or_more_ints(arr, 1, n);
}


/*
run:

1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 2
1 + 1 + 3
1 + 2 + 2
1 + 4
2 + 3

*/

 



answered Aug 3, 2024 by avibootz
...