A partition of an integer n is a way of writing n as a sum of positive integers. For
example, for n=7, a partition is 1+1+5. I need a program that finds all the
How about this? Have an additional argument passed as reference for r, and increment r each time within the recursion block?
#include
#include
using namespace std;
void print (vector& v, int level){
for(int i=0;i<=level;i++)
cout << v[i] << " ";
cout << endl;
}
void part(int n, vector& v, int level, int &r){
int first; /* first is before last */
if(n<1) return ;
v[level]=n;
print(v, level);
first=(level==0) ? 1 : v[level-1];
for(int i=first;i<=n/2;i++){
v[level]=i; /* replace last */
r++;
part(n-i, v, level+1, r);
}
}
int main(){
int num;
cout << "Enter a number:";
cin >> num;
int r = 0;
vector v(num);
part(num, v, 0, r);
cout << "r = " << r << endl;
}
Output comes as:
Enter a number:5
1 4
1 1 3
1 1 1 2
1 1 1 1 1
1 2 2
2 3
r = 6
Is this what you are looking for?