How to get the permutation of a number in Java

Overview

A permutation is the number of ways by which we can arrange a set or an object in a definite order. The mathematical formula to calculate a permutation is given below:

The formula for permutation in Java

Parameters

  • P: This is the number of permutations.
  • n: This is the number of objects.
  • r: This is the number of objects selected.

We must use the above formula to get the permutation for multiple objects. We obtain the permutation by defining the factorial for n and n-r.

Here is the syntax to get the factorial using a for loop.

Syntax

for(counter; counter <= number; counter++)
{
result = result * counter;
}
Syntax for finding the factorial of a number

Parameters

counter: This represents a counter. The function will use it for looping.

number: This is the input number for which we're trying to find the factorial.

Code

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 = 7;
int n2 = 4;
// create number of the objects are taken at a time
int r1 = 3;
int r2 = 2;
// get the permutation based on the mathematical formula
System.out.println(factorial(n1)/(factorial(r1)*factorial(n1-r1)));
System.out.println(factorial(n2)/(factorial(n2-r2)));
}
}

Explanation

  • Line 3: We create a factorial() function that takes an integer number and returns its factorial.
  • Lines 15 and 16: We create and initialize variables for the number of objects we want to get combinations of.
  • Lines 19 and 20: We create and initialize the number of objects taken at a particular time for every selection.
  • Lines 23 and 24: We use the mathematical formula for combinations to obtain the permutations and print the values to the console.

Free Resources