Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
combination
function
communitycreator

How to get the combination of a number in Java using a function

okwudili onyejiaku

Overview

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.

Formula for combination in mathematics

From the illustration above, we can see that:

  • nCr: Represents the number of combinations.
  • n : Represents the total number of objects.
  • r: Represents the number of chosen objects.

Syntax

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

Parameters

The parameters in the loop are as follows:

  • counter: Represents a counter. It will be used for looping.
  • number: Represents the number whose factorial we want to find.

Code example

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

Explanation

  • 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
RELATED COURSES

View all Courses

Keep Exploring