/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jmathexpr.arithmetic.func;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import jmathexpr.AbstractExpression;
import jmathexpr.Expression;
import jmathexpr.Precedence;
import jmathexpr.func.Function;
import jmathexpr.arithmetic.integer.IntegerNumber;
import jmathexpr.arithmetic.natural.NaturalNumber;
import jmathexpr.arithmetic.natural.Naturals;
import jmathexpr.set.NTuple;
import jmathexpr.set.OrderedPair;
import jmathexpr.set.Tuple;
/**
* This class represents the LCM (least common multiplier) of two or more natural
* numbers.
*
* @author Elemér Furka
*/
public class Lcm extends AbstractExpression implements Function {
private final Tuple args;
/**
* Creates a new LCM object with two arguments.
*/
public Lcm(Expression a, Expression b) {
args = new OrderedPair(a, b);
}
public Lcm(Collection<Expression> args) {
this.args = new NTuple(args);
}
@Override
public Expression evaluate() {
List<NaturalNumber> naturals = new ArrayList();
Expression n;
for (int i = 1; i <= args.length(); i++) {
n = args.at(i);
if (n instanceof NaturalNumber) {
naturals.add((NaturalNumber) n);
} else if (n instanceof IntegerNumber) {
naturals.add(((IntegerNumber) n).toNatural());
} else {
throw new IllegalStateException("Cannot convert to natural number: " + n);
}
}
return Naturals.lcm(new NTuple(naturals));
}
@Override
public List<Expression> getChildren() {
return args.getChildren();
}
@Override
public Precedence getPrecedence() {
return Precedence.Function;
}
@Override
public String toString() {
return args.toString();
}
@Override
public String toUnicode() {
return toString();
}
}