Write a Java program that will output the number of distinct ways in which you c
ID: 3759600 • Letter: W
Question
Write a Java program that will output the number of distinct ways in which you can pick k objects out of a set of n objects (both n and k should be positive integers). This number is given by the following formula:
C(n, k) = n! / (k! * (n - k)!)
Your program should use 2 value-returning methods:
1. The first method should be called factorial and should return n! (Take a look at Problem#2 in Lab #6) The factorial of a positive integer n is the product of all integers from 1 to n. You can express the factorial of a positive integer n (in mathematics this is denoted by n!) using the following formula: n! = 1 * 2 * 3 * ... * (n - 1) * n
The following specifications describe a method that computes factorials:
Input parameter: int n (where n is the number whose factorial is to be computed)
Return: the factorial of n, which is computed using the formula for n!
2. The second method should be called combinations and should return n! / (k! * (n - k)!). This method should call factorial.
The following specifications describe a method that computes combinations:
Input parameters: int n, k
Return: n choose k, which is computed using the formula for C(n, k).
Explanation / Answer
import java.util.Scanner;
public class Combination {
public static int factorial(int n) {
int fac=1;
for (int i = 1; i <= n; i++) {
fac = fac*i;
}
return fac;
}
public static int combinations(int n, int k) {
return factorial(n)/ (factorial(k)*factorial(n-k));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter n: ");
int n = sc.nextInt();
System.out.print("Enter k: ");
int k = sc.nextInt();
System.out.println("Combination of ("+n+", "+k+") is: "+combinations(n, k));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.