-1

I want to get the factorial value of a number. I read in a wiki that I can expect the result of 5! to be 5x4x3x2x1 = 120. Now how can I get that in Java?

BigFraction g = new BigFraction(5);
System.out.println(g.getNumerator());

This prints just 5.

In the end i want to calculate combinations in a network:

network

Which has the following formula:

example from wiki

Perception
  • 79,279
  • 19
  • 185
  • 195
clankill3r
  • 9,146
  • 20
  • 70
  • 126

3 Answers3

1

You seem to be confusing fractions and factorials.

If you want the factorial, you can use ArithmeticUtils.factorial for that:

long factorial = ArithmeticUtils.factorial(5);
System.out.println(factorial); // "120"
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Use Guava's BigIntegerMath.

To calculate the factorial i.e. n!:

BigInteger factorial = BigIntegerMath.factorial(n);

To calculate the binomial i.e. n! / (k! (n - k)!):

BigInteger binomial = BigIntegerMath.binomial(n, k);

(Similar functionality for int and long is available in IntMath and LongMath respectively.)

dogbane
  • 266,786
  • 75
  • 396
  • 414
1

By the way, why not just use the plain old formula:

x=n*(n-1)/2

Where n is the number of vertices.

For this simple task, you don't have to use a computationally intensive function as a factorial...

ppeterka
  • 20,583
  • 6
  • 63
  • 78