-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
  • 77,470
  • 19
  • 176
  • 187
clankill3r
  • 8,471
  • 17
  • 67
  • 115

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
  • 959,406
  • 173
  • 1,780
  • 1,769
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
  • 254,755
  • 72
  • 386
  • 405
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,372
  • 6
  • 62
  • 77