C++ Program to Generate All Unique Partitions of an Integer

This C++ Program demonstrates Generating All Unique Partitions of an Integer.

Here is source code of the C++ Program to demonstrate the Generation of All Unique Partitions of an Integer. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

/*

* C++ Program to Generate All Unique Partitions of an Integer

*/

#include<iostream>

usingnamespace std;

/*

* print an array p[] of size 'n'

*/

void printArray(int p[], int n)

{

for(int i =0; i < n; i++)

cout<< p[i]<<" ";

cout<< endl;

}

void printAllUniqueParts(int n)

{

int p[n];

int k =0;

p[k]= n;

while(true)

{

printArray(p, k +1);

int rem_val =0;

while(k >=0&& p[k]==1)

{

rem_val += p[k];

k--;

}

if(k <0)

return;

p[k]--;

rem_val++;

while(rem_val > p[k])

{

p[k+1]= p[k];

rem_val = rem_val - p[k];

k++;

}

p[k+1]= rem_val;

k++;

}

}

/*

* Main

*/

int main()

{

int value;

while(1)

{

cout<<"Enter an Integer(0 to exit): ";

cin>>value;

if(value ==0)

break;

cout<<"All Unique Partitions of "<<value<<endl;

printAllUniqueParts(value);

cout<<endl;

}

return0;

}

$ g++ unique_partitions.cpp
$ a.out
Enter an Integer(0 to exit): 2
All Unique Partitions of 2211
Enter an Integer(0 to exit): 3
All Unique Partitions of 3321111
Enter an Integer(0 to exit): 4
All Unique Partitions of 4431222111111
Enter an Integer(0 to exit): 5
All Unique Partitions of 554132311221211111111
Enter an Integer(0 to exit): 7
All Unique Partitions of 7761525114342141113313223211311112221221112111111111111
Enter an Integer(0 to exit): 0------------------(program exited with code: 1)
Press return to continue

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

If you wish to look at all C++ Programming examples, go to C++ Programs.