342 Intermediate C Programming
lim
n→∞
2
n
n
p
= ∞. (21.1)
This means that the exponential function eventually grows faster than any polynomial.
There is always a value of n such that 2
n
is larger than n
p
, no matter what p is. This can
be proved by using the L’Hospital’s Rule from calculus.
This section asks you to write a program that counts the number of subsets whose sums
are equal to the given value k. Instead of finding a sophisticated algorithm, the section uses
a simple solution that enumerates all subsets (excluding the empty set). The program must
read the value of k and then the set’s elements from a file. After reading the data from the
file, the program checks whether the set is valid. The set is invalid if any element is zero
or negative, or if two elements have the same value. If the set is invalid, then the program
does not attempt to solve the subset sum problem.
If the set is valid, then the program generates all possible subsets of the given set. This
program first calculates the number of possible subsets. If a set has n elements, then there
are 2
n
subsets including the empty set. If each subset is given a number, then the subsets
are numbers between 0 and 2
n
− 1 inclusively. The empty set is not considered because
k 6= 0, and thus we only need to consider the subsets labeled 1 to 2
n
− 1. Note that since
each number corresponds to a subset, and we will check to total sum of the numbers in that
subset, we have each number corresponding to a subset sum. The following table explains
how the numbers are related to the subset sums:
Value Sum
1 a
1
2 a
2
3 a
1
+ a
2
4 a
3
5 a
1
+ a
3
6 a
2
+ a
3
7 a
1
+ a
2
+ a
3
8 a
4
.
.
.
.
.
.
2
n
− 1 a
1
+ a
2
+ a
3
+ ... + a
n
The test generator is restricted to at most 31 elements so that 2
n
can fit in a four-byte
integer. This following is a sample implementation of the sequential program as described
above. First is the main function:
// main . c1
#in clude < pthread .h >2
#in clude < stdio .h >3
#in clude < stdlib .h >4
#in clude " subset s um .h "5
int main ( i n t argc , char * argv [])6
{7
// read the data from a file8
i f ( argc < 2)9
{10
printf (" Need input file name n" );11
return EXIT _FAILUR E ;12
}13
FILE * fptr = fopen ( argv [1] , "r ");14