Files
paradigms/java/expression/Log.java
2026-04-08 21:25:17 +03:00

46 lines
1.5 KiB
Java

package expression;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* @author Doschennikov Nikita (me@fymio.us)
*/
public class Log extends AbstractBinaryOperation {
public Log(AbstractExpression l, AbstractExpression r) { super(l, r); }
@Override protected String getOperator() { return "//"; }
@Override protected int getPriority() { return 3; }
@Override protected boolean isRightAssoc() { return true; }
@Override
protected int applyInt(int a, int b) {
if (a <= 0) throw new ArithmeticException("logarithm of non-positive number");
if (b <= 1) throw new ArithmeticException("logarithm base must be > 1");
int result = 0;
int power = 1;
while (power <= a / b) {
power *= b;
result++;
}
return result;
}
@Override
protected BigInteger applyBi(BigInteger a, BigInteger b) {
if (a.signum() <= 0) throw new ArithmeticException("logarithm of non-positive number");
if (b.compareTo(BigInteger.TWO) < 0) throw new ArithmeticException("logarithm base must be > 1");
int result = 0;
BigInteger power = BigInteger.ONE;
while (power.multiply(b).compareTo(a) <= 0) {
power = power.multiply(b);
result++;
}
return BigInteger.valueOf(result);
}
@Override
protected BigDecimal applyBd(BigDecimal a, BigDecimal b) {
throw new UnsupportedOperationException("log not supported for BigDecimal");
}
}