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

67 lines
1.6 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;
2016-09-02 20:32:37 +02:00
/**
* Euler totient function.
2018-09-22 11:17:30 +02:00
*
2016-09-02 20:32:37 +02:00
* @see <a href="http://oeis.org/A000010">A000010</a> in the OEIS.
* @since 2008-10-14
* @since 2012-03-04 Adapted to new Ifactor representation.
* @author Richard J. Mathar
*/
public class EulerPhi {
/**
* Default constructor.
* Does nothing().
*/
public EulerPhi() {}
2016-03-15 10:41:39 +01:00
2016-09-02 20:32:37 +02:00
/**
* Compute phi(n).
2018-09-22 11:17:30 +02:00
*
2016-09-02 20:32:37 +02:00
* @param n
* The positive argument of the function.
* @return phi(n)
*/
2018-09-22 11:17:30 +02:00
public BigInteger at(final int n) {
2016-09-02 20:32:37 +02:00
return at(new BigInteger("" + n));
} /* at */
2016-03-15 10:41:39 +01:00
2016-09-02 20:32:37 +02:00
/**
* Compute phi(n).
2018-09-22 11:17:30 +02:00
*
2016-09-02 20:32:37 +02:00
* @param n
* The positive argument of the function.
* @return phi(n)
*/
2018-09-22 11:17:30 +02:00
public BigInteger at(final BigInteger n) {
2018-09-28 11:39:28 +02:00
if (n.compareTo(BigInteger.ZERO) <= 0) {
2016-09-02 20:32:37 +02:00
throw new ArithmeticException("negative argument " + n + " of EulerPhi");
2018-09-28 11:39:28 +02:00
}
final Ifactor prFact = new Ifactor(n);
2016-09-02 20:32:37 +02:00
BigInteger phi = n;
2018-09-28 11:39:28 +02:00
if (n.compareTo(BigInteger.ONE) > 0) {
2016-09-02 20:32:37 +02:00
for (int i = 0; i < prFact.primeexp.size(); i += 2) {
final BigInteger p = new BigInteger(prFact.primeexp.elementAt(i).toString());
final BigInteger p_1 = p.subtract(BigInteger.ONE);
2016-09-02 20:32:37 +02:00
phi = phi.multiply(p_1).divide(p);
}
2018-09-28 11:39:28 +02:00
}
2016-09-02 20:32:37 +02:00
return phi;
} /* at */
2016-03-15 10:41:39 +01:00
2016-09-02 20:32:37 +02:00
/**
* Test program.
* It takes one argument n and prints the value phi(n).<br>
* java -cp . org.nevec.rjm.EulerPhi n<br>
2018-09-22 11:17:30 +02:00
*
2016-09-02 20:32:37 +02:00
* @since 2006-08-14
*/
2018-09-22 11:17:30 +02:00
public static void main(final String[] args) throws ArithmeticException {
final EulerPhi a = new EulerPhi();
2018-09-22 11:17:30 +02:00
final int n = new Integer(args[0]).intValue();
2016-09-02 20:32:37 +02:00
System.out.println("phi(" + n + ") = " + a.at(n));
}
2016-03-15 10:41:39 +01:00
} /* EulerPhi */