Calculate Permutation and Combination in Java

Permutation and combination of two numbers n and r are calculated as nPr = !n / !(n – r) and nCr = !n / (!(n – r) * !r) where permutation is denoted as nPr and combination is denoted as nCr.

The nPr means permutation of n and r and nCr means combination of n and r.

Also note that !n means the factorial of n.

Factorial of N is the product of all the integers from 1 to N.

Factorial of 0 is 1.

Write a program in Java to accept two numbers n and r from the user and calculate their permutation and combination by using the above formula.

nPr is:39916800
nCr is:11

Display an appropriate message if n or r is less than 0.

class PermutationCombination{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(;
        System.out.print("n = ");
        int n = Integer.parseInt(br.readLine());
        System.out.print("r = ");
        int r = Integer.parseInt(br.readLine());
        if(n < 0 || r < 0){
            System.out.println("Invalid values!");
        long npr = f(n) / f(n - r);
        long ncr = f(n) / (f(n - r) * f(r));
        System.out.println("nPr = " + npr);
        System.out.println("nCr = " + ncr);
    public static long f(int n){
        long result = 1L;
        for(int i = 1; i <= n; i++)
            result *= i;
        return result;

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.