Program: 8. Find A Subset of A Given Set S (SL, s2,....., SN) of N Positive Integers Whose Sum Is Equal To A Given
Program: 8. Find A Subset of A Given Set S (SL, s2,....., SN) of N Positive Integers Whose Sum Is Equal To A Given
8. Find a subset of a given set S = {sl, s2,.....,sn} of n positive integers whose sum is equal to a given
positive integer d. For example, if S={1, 2, 5, 6, 8} and d = 9 there are two
solutions{1,2,6}and{1,8}.A suitable message is to be displayed if the given problem instance doesn't
have a solution.
Program
#include<iostream.h>
#include<conio.h>
#include<math.h>
void sumofsub(int num,int n,int x[])
{
int i;
for(i=1;i<=n;i++)
x[i]=0;
for(i=n;num!=0;i--)
{
x[i]=num%2;
num=num/2;
}
}
void main()
{
int a[20],x[20],n,j,i,d,sum,present=0;
clrscr();
cout<<"Enter the number of Elements:";
cin>>n;
cout<<"\nEnter the Elements in Ascending Order:";
for(i=1;i<=n;i++)
cin>>a[i];
cout<<"\nEnter the Sum value:";
cin>>d;
for(i=1;i<=pow(2,n)-1;i++)
{
sumofsub(i,n,x);
sum=0;
for(j=1;j<=n;j++)
if(x[j]==1)
sum=sum+a[j];
if(d==sum)
{
cout<<"\nSubset={";
Prashanth Kumar
10CSL47
}
}
if(present==0)
cout<<"\nSolution doesn't Exist";
getch();
}
/*************************************OUTPUT***************************************/
Prashanth Kumar