WarpPI/core/src/main/java/org/nevec/rjm/Factorial.java

80 lines
1.7 KiB
Java
Raw Normal View History

2016-09-02 20:32:37 +02:00
package org.nevec.rjm;
2016-03-15 10:41:39 +01:00
import java.math.BigInteger;
import java.util.Vector;
2016-09-02 20:32:37 +02:00
/**
* Factorials.
2018-09-22 11:17:30 +02:00
*
2016-09-02 20:32:37 +02:00
* @since 2006-06-25
* @since 2012-02-15 Storage of the values based on Ifactor, not BigInteger.
* @author Richard J. Mathar
*/
public class Factorial {
/**
* The list of all factorials as a vector.
*/
2017-01-17 22:32:40 +01:00
static Vector<Ifactor> a = new Vector<>();
2016-03-15 10:41:39 +01:00
2016-09-02 20:32:37 +02:00
/**
* ctor().
* Initialize the vector of the factorials with 0!=1 and 1!=1.
*/
public Factorial() {
2018-09-22 11:17:30 +02:00
if (Factorial.a.size() == 0) {
Factorial.a.add(Ifactor.ONE);
Factorial.a.add(Ifactor.ONE);
2016-09-02 20:32:37 +02:00
}
} /* ctor */
2016-03-15 10:41:39 +01:00
2016-09-02 20:32:37 +02:00
/**
* Compute the factorial of the non-negative integer.
2018-09-22 11:17:30 +02:00
*
2016-09-02 20:32:37 +02:00
* @param n
* the argument to the factorial, non-negative.
* @return the factorial of n.
*/
2018-09-22 11:17:30 +02:00
public BigInteger at(final int n) {
2016-09-02 20:32:37 +02:00
/*
* extend the internal list if needed.
*/
growto(n);
2018-09-22 11:17:30 +02:00
return Factorial.a.elementAt(n).n;
2016-09-02 20:32:37 +02:00
} /* at */
2016-03-15 10:41:39 +01:00
2016-09-02 20:32:37 +02:00
/**
* Compute the factorial of the non-negative integer.
2018-09-22 11:17:30 +02:00
*
2016-09-02 20:32:37 +02:00
* @param n
* the argument to the factorial, non-negative.
* @return the factorial of n.
*/
2018-09-22 11:17:30 +02:00
public Ifactor toIfactor(final int n) {
2016-09-02 20:32:37 +02:00
/*
* extend the internal list if needed.
*/
growto(n);
2018-09-22 11:17:30 +02:00
return Factorial.a.elementAt(n);
2016-09-02 20:32:37 +02:00
} /* at */
2016-03-15 10:41:39 +01:00
2016-09-02 20:32:37 +02:00
/**
* Extend the internal table to cover up to n!
2018-09-22 11:17:30 +02:00
*
2016-09-02 20:32:37 +02:00
* @param n
* The maximum factorial to be supported.
* @since 2012-02-15
*/
2018-09-22 11:17:30 +02:00
private void growto(final int n) {
2016-09-02 20:32:37 +02:00
/*
* extend the internal list if needed. Size to be 2 for n<=1, 3 for n<=2
* etc.
*/
2018-09-22 11:17:30 +02:00
while (Factorial.a.size() <= n) {
final int lastn = Factorial.a.size() - 1;
2016-09-02 20:32:37 +02:00
final Ifactor nextn = new Ifactor(lastn + 1);
2018-09-22 11:17:30 +02:00
Factorial.a.add(Factorial.a.elementAt(lastn).multiply(nextn));
2016-09-02 20:32:37 +02:00
}
} /* growto */
2016-03-15 10:41:39 +01:00
} /* Factorial */