Trusted answers to developer questions

okwudili onyejiaku

We can get the combination of a number by creating a function. A **combination** is used to find the number of possible arrangements of objects without regarding the order in which they are selected.

We will use the mathematical formula below where we use some factorials `n!`

, `r!`

, and `(n-r)!`

. Hence, we will create a function that returns the factorial.

From the illustration above, we can see that:

_{n}**C**_{r}**:**Represents the number of combinations.

: Represents the total number of objects.**n**

: Represents the number of chosen objects.**r**

The syntax for finding the factorial of a number is as follows:

for(counter; counter <= number; counter++) { result = result * counter; }

Syntax for finding the factorial of a number

The parameters in the loop are as follows:

: Represents a counter. It will be used for looping.**counter**

: Represents the number whose factorial we want to find.**number**

Let's look at a code example below:

class HelloWorld { // create the factorial function public static int factorial(int num){ int result = 1, counter; // create for loop for(counter=1; counter<=num; counter++){ result = result*counter; } return result; } public static void main( String args[] ) { // create some numbers of objects we want to get the combination int n1 = 10; int n2 = 4; // create number of the objects are taken at a time int r1 = 3; int r2 = 2; // get the combination based on the mathematical formula System.out.println(factorial(n1)/(factorial(r1)*factorial(n1-r1))); System.out.println(factorial(n2)/(factorial(r2)*factorial(n2-r2))); } }

Get the combination of a number

**Line 3**: We create the factorial function, which takes an integer number and returns its factorial.**Lines 15 - 16**: We create and initialize variables for the number of objects we want to get the combinations for.**Lines 19 - 20**: We create the number of objects taken at a particular time for every selection.**Lines 23 - 24**: With the mathematical formula for combination, as explained earlier on, we get the combinations and print the values to the console.

RELATED TAGS

java

combination

function

communitycreator

CONTRIBUTOR

okwudili onyejiaku

RELATED COURSES

View all Courses

Keep Exploring

Related Courses