Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

How to write a program that Calculating Combinations. Write a program to compute C(n, r). This function is known as the choose function, and is

How to write a program that Calculating Combinations.

Write a program to compute C(n, r). This function is known as the choose function, and is defined as the number of r element subsets of an n element set. So C(5, 2) = 10 because there are ten possible two element subsets from a set of 5 elements. Similarly, C(4, 1) = 4, C(4, 4) = 1, and C(4, 0) = 1.

Mathematically the choose function is defined as:

image text in transcribed

where n and r are non-negative integers (including zero), and "!" means factorial. So C(5, 2) = 5! / (2! * 3!) = 120 / (2 * 6) = 120 / 12 = 10. Recall that 0! (zero factorial) is defined to be 1 (one).

You must use at least the following four methods in your program. You can make them all public static methods if you wish.

1. void main(String[] args) Prompts the user to enter a pair of integers and stores them in variables n and r respectively. Calls the method check to make sure n and r are each non-negative and that n >= r, exiting the program if not Next, call the method choose that calculates and returns C(n,r) Finally, display the result

2. boolean check ( int n, int r ) Verify that both n and r are non-negative( >= 0), and that n is greater than or equal to r (i.e. n >= r). If so, return true; if not, print an appropriate error message and return false.

3. int fact ( int num ) Compute and return num! (that is, the factorial of num). This is the same calculation that you had to perform in the previous homework.

4. int C ( int n, int r ) Compute and return C( n, r ) as described in the equation above. This function should call the fact method three times.

Note: You can use variables of type long to make the program work for larger values of n and r

C(n, r) = r!(n-r)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions