Wanted to know how this program functions.
tried hard to figure out the code,but couldn't.
can someone explain to me step by step?
FIGURE 5-5 Program to compute the combinations function C(n, k)
/*
* File: Combinations.java
* -----------------------
* This program computes the mathematical combinations function
* C(n, k), which is the number of ways of selecting k objects
* from a set of n distinct objects.
*/
import acm.program.*;
publicclass Combinations extends ConsoleProgram {
/* Runs the program */
publicvoid run() {
int n = readInt("Enter number of objects in the set (n): ");
int k = readInt("Enter number to be chosen (k): ");
println("C(" + n + ", " + k + ") = " + combinations(n, k));
}
/*
* Returns the mathematical combinations function C(n, k),
* which is the number of ways of selecting k objects
* from a set of n distinct objects.
*/
privateint combinations(int n, int k) {
return factorial(n) / (factorial(k) * factorial(n - k));
}
/*
* Returns the factorial of n, which is defined as the
* product of all integers from 1 up to n.
*/
privateint factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
Parastar wrote:
tried hard to figure out the code,but couldn't.
Where did you get stuck? How did you try to "figure out the code"? If you haven't already, try stepping through it with a debugger. Or (arguably) better yet, step through it yourself using a piece of paper and a pencil to keep track of what's happening.
Parastar wrote:
... how this program functions.
tried hard to figure out the code, but couldn't.
What part of it do you not understand?
/*
* Returns the mathematical combinations function C(n, k),
* which is the number of ways of selecting k objects
* from a set of n distinct objects.
*/
privateint combinations(int n, int k) {
return factorial(n) / (factorial(k) * factorial(n - k));
}
/*
* Returns the factorial of n, which is defined as the
* product of all integers from 1 up to n.
*/
privateint factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}