Search code examples
javaalgorithmfor-looppermutationfactorial

Permutation related algorithm


Good day. I need some help with looking for the NUMBER OF possible permutations using java.

For example, if n = 3 and k = 3 (n for the length of the characters and k for the number of characters you would want to take to permute).

Our formula would be: nPk = n! / (n-k)!

nPk = 6 / (3 - 3)!

= 6 / 0!

= 6 (it means 6 possible permutations)

Because n = 3!, therefore:

3! = 3 * 2 * 1

= 6 ( n = 6 )

I just need to know the algorithm on how to do 6! in java using for-loops only. Thank you :)


Solution

  • please see,

    int n=3, fact = 1;
    for (; n > 0; n--) {
        fact = fact * n;
    }
    
    System.out.println("The result is " + fact);