TASK: Count subsets of size K from a set of size N.
COMMENT: Let A, B, C, D, E and F be the N = 6 elements of a set. Suppose we wish to choose K = 2 of these letters to form a subset. It turns out there are 15 ways to do this, which we symbolize by C(6,2)=15. In general, C(N,K) is supposed to count the number of distinct subsets of size K from a set of size N. As a convention, we define C(N,0)=1 (there's only one way to take nothing from a set.)
One formula for C(N,K) is
C(N,K) = N! / ( K! (N-K)! )where "!" indicates the factorial function: N! = 1 * 2 * 3 * ... * N.
Another formula for C(N,K) uses a recurrence.
C(N,0) = 1 C(N,1) = C(N,0) * N / 1 C(N,2) = C(N,1) * (N-1) / 2 ... C(N,I) = C(N,I-1) * (N-I+1) / I <-- the general formula ... C(N,K) = C(N,K-1) * (N-K+1) / K
INSTRUCTIONS:
Use the input() statement to get values of n and k. N should be positive, and k should be between 0 and n. Define a variable "cnk" and start it at 1. Create a for loop in which i goes from 1 to k. Use the "general formula" to update the value of cnk, writing: cnk = cnk * ? / ?; end your FOR loop fprintf ( ' C(%d,%d) = %d\n', n, k, cnk );
SUBMIT: Your work should be stored in a script file called "hw021.m". Your script file should begin with at least three comment lines:
% hw021.m % YOUR NAME % This script (describe what it does) % Add any comments here that you care to make.If this problem is part of an assignment, then submit it to Canvas.