Example usage for org.apache.commons.math.util MathUtils gcd

List of usage examples for org.apache.commons.math.util MathUtils gcd

Introduction

In this page you can find the example usage for org.apache.commons.math.util MathUtils gcd.

Prototype

public static long gcd(final long p, final long q) 

Source Link

Document

Gets the greatest common divisor of the absolute value of two numbers, using the "binary gcd" method which avoids division and modulo operations.

Usage

From source file:com.xiantrimble.combinatorics.LeadingElementPerportionTest.java

@Test
public void twoElementsPerportional() {
    int[] leadingOnes = new int[permutations.getK()];
    int[] leadingTwos = new int[permutations.getK()];
    for (Element[] element : permutations) {
        for (int i = 0; i < element.length; i++) {
            leadingOnes[i] += element[i] == ONE ? 1 : 0;
            leadingTwos[i] += element[i] == TWO ? 1 : 0;
        }/*ww w. j  a  v a 2  s  .c  o  m*/
    }

    // Turn the leading arrays into proper fractions.
    int[] leadingGcd = new int[permutations.getK()];
    for (int i = 0; i < permutations.getK(); i++) {
        leadingGcd[i] = MathUtils.gcd(leadingOnes[i], leadingTwos[i]);
        leadingOnes[i] /= leadingGcd[i];
        leadingTwos[i] /= leadingGcd[i];
    }

    int totalOnes = permutations.getDomain().get(0).size();
    int totalTwos = permutations.getDomain().get(1).size();

    // Turn the total into a proper fraction.
    int totalGcd = MathUtils.gcd(totalOnes, totalTwos);
    totalOnes /= totalGcd;
    totalTwos /= totalGcd;

    for (int i = 0; i < permutations.getK(); i++) {
        assertEquals("The wrong perportion of ones were found at index " + i, totalOnes, leadingOnes[i]);
        assertEquals("The wrong perportion of twos were found at index " + i, totalTwos, leadingTwos[i]);
    }
}

From source file:com.xiantrimble.combinatorics.LeadingElementPerportionTest.java

/**
 * if we make kM[i]/kS a proper fraction, can we always apply the denominator first to kS?
 * This test demonstrates that this is safe.  Applying this first will allow us to
 * approach Long.MAX_LONG sizes safely.//ww  w  .j  a  v  a2  s  .  c om
 */
@Test
public void alwaysDivisible() {
    long size = permutations.size();
    int kTotalM = permutations.getDomain().totalSize();
    for (int m : permutations.getDomain().toMultiplicity()) {
        long gcd = MathUtils.gcd(kTotalM, m);
        long den = kTotalM / gcd;
        assertEquals("Greatest common divisor is not denominator", den, MathUtils.gcd(size, den));
    }
}

From source file:com.xiantrimble.combinatorics.LeadingElementPerportionTest.java

@Test
public void relativeComputation() {
    long kS = permutations.size();
    int kTotalM = permutations.getDomain().totalSize();
    int[] kM = permutations.getDomain().toMultiplicity();
    for (int i = 0; i < kM.length; i++) {
        long gcd = MathUtils.gcd(kTotalM, kM[i]);
        long num = kM[i] / gcd;
        long den = kTotalM / gcd;
        long s = (kS / den) * num;

        // compute the expected result.
        int[] m = Arrays.copyOf(kM, kM.length);
        m[i]--;//from w ww  .  jav a2 s .co  m
        long expected = factory.getMathUtils().p(permutations.getK() - 1, m);

        // verify that the computed size is the same as the expected size.
        assertEquals(expected, s);
    }
}

From source file:geogebra.kernel.AlgoSurdText.java

protected void PSLQappend(StringBuilder sb, double num) {
    double[] numPowers = { num * num, num, 1.0 };
    int[] coeffs = PSLQ(numPowers, Kernel.STANDARD_PRECISION, 10);

    if (coeffs[0] == 0 && coeffs[1] == 0 && coeffs[2] == 0) {
        sb.append("\\text{" + app.getPlain("undefined") + "}");
    } else if (coeffs[0] == 0) {
        //coeffs[1]: denominator;  coeffs[2]: numerator
        int denom = coeffs[1];
        int numer = -coeffs[2];
        Fractionappend(sb, numer, denom);

    } else {/*from  w ww. ja  va 2s .  co  m*/

        //coeffs, if found, shows the equation coeffs[2]+coeffs[1]x+coeffs[0]x^2=0"
        //We want x=\frac{a +/- b1\sqrt{b2}}{c}
        //where  c=coeffs[0], a=-coeffs[1], b=coeffs[1]^2 - 4*coeffs[0]*coeffs[2]
        int a = -coeffs[1];
        int b2 = coeffs[1] * coeffs[1] - 4 * coeffs[0] * coeffs[2];
        int b1 = 1;
        int c = 2 * coeffs[0];

        if (b2 <= 0) { //should not happen!
            sb.append("\\text{" + app.getPlain("undefined") + "}");
            return;
        }

        //free the squares of b2
        while (b2 % 4 == 0) {
            b2 = b2 / 4;
            b1 = b1 * 2;
        }
        for (int s = 3; s <= Math.sqrt(b2); s += 2)
            while (b2 % (s * s) == 0) {
                b2 = b2 / (s * s);
                b1 = b1 * s;
            }

        if (c < 0) {
            a = -a;
            c = -c;
        }

        boolean positive;
        if (num > (a + 0.0) / c) {
            positive = true;
            if (b2 == 1) {
                a += b1;
                b1 = 0;
                b2 = 0;
            }
        } else {
            positive = false;
            if (b2 == 1) {
                a -= b1;
                b1 = 0;
                b2 = 0;
            }
        }

        int gcd = MathUtils.gcd(MathUtils.gcd(a, b1), c);
        if (gcd != 1) {
            a = a / gcd;
            b1 = b1 / gcd;
            c = c / gcd;
        }

        //when fraction is needed
        if (c != 1)
            sb.append("\\frac{");

        if (a != 0)
            sb.append(kernel.format(a));

        //when the radical is surd
        if (b2 != 0) {
            if (positive) {
                if (a != 0)
                    sb.append("+");
            } else {
                sb.append("-");
            }

            if (b1 != 1)
                sb.append(kernel.format(b1));
            sb.append("\\sqrt{");
            sb.append(kernel.format(b2));
            sb.append("}");
        }

        //when fraction is needed
        if (c != 1) {
            sb.append("}{");
            sb.append(kernel.format(c));
            sb.append("}");
        }
    }

}

From source file:dr.evomodel.arg.coalescent.ARGUniformPrior.java

private static double reduceThenDivide(int[] top, int[] bottom) {

    if (false) {//  w w w . j a  v  a2 s .  c o  m
        for (int i = 0; i < top.length; i++) {
            for (int j = 0; j < bottom.length; j++) {
                int gcd = MathUtils.gcd(top[i], bottom[j]);

                if (gcd > 1) {
                    top[i] = top[i] / gcd;
                    bottom[j] = bottom[j] / gcd;
                }
            }

        }

    }

    Arrays.sort(top);
    Arrays.sort(bottom);

    double a = 1;
    for (int i = 0; i < top.length; i++)
        a *= (double) top[i] / bottom[i];
    return a;

}

From source file:com.zavakid.mushroom.impl.MetricsSystemImpl.java

private synchronized void configureSinks() {
    sinkConfigs = config.getInstanceConfigs(MetricsConfig.SINK_KEY);
    int confPeriod = 0;
    for (Entry<String, MetricsConfig> entry : sinkConfigs.entrySet()) {
        MetricsConfig conf = entry.getValue();
        int sinkPeriod = conf.getInt(MetricsConfig.PERIOD_KEY, MetricsConfig.PERIOD_DEFAULT);
        confPeriod = confPeriod == 0 ? sinkPeriod : MathUtils.gcd(confPeriod, sinkPeriod);
        String sinkName = entry.getKey();
        LOG.debug("sink " + sinkName + " config:\n" + conf);
        try {//from   www . j a  va  2 s.  com
            MetricsSinkAdapter sa = newSink(sinkName, conf.getString(MetricsConfig.DESC_KEY, sinkName), conf);
            // we allow config of later registered sinks
            if (sa != null) {
                sa.start();
                sinks.put(sinkName, sa);
            }
        } catch (Exception e) {
            LOG.warn("Error creating " + sinkName, e);
        }
    }
    period = confPeriod > 0 ? confPeriod
            : config.getInt(MetricsConfig.PERIOD_KEY, MetricsConfig.PERIOD_DEFAULT);
}

From source file:geogebra.common.kernel.cas.AlgoSurdText.java

/**
 * Goal: modifies a StringBuilder object sb to be a radical up to quartic
 * roots The precision is adapted, according to setting
 * /*w  w  w  .  j  a  v  a2s.c o m*/
 * @param sb
 * @param num1
 * @param tpl
 */
protected void PSLQappendQuartic(StringBuilder sb, double num1, StringTemplate tpl) {
    double[] numPowers = new double[5];
    double temp = 1.0;

    for (int i = 4; i >= 0; i--) {
        numPowers[i] = temp;
        temp *= num1;
    }

    getKernel();
    int[] coeffs = PSLQ(numPowers, Kernel.STANDARD_PRECISION, 10);

    if (coeffs[0] == 0 && coeffs[1] == 0) {

        if (coeffs[2] == 0 && coeffs[3] == 0 && coeffs[4] == 0) {
            appendUndefined(sb, tpl, num1);
        } else if (coeffs[2] == 0) {
            // coeffs[1]: denominator; coeffs[2]: numerator
            int denom = coeffs[3];
            int numer = -coeffs[4];
            Fractionappend(sb, numer, denom, tpl);

        } else {

            // coeffs, if found, shows the equation
            // coeffs[2]+coeffs[1]x+coeffs[0]x^2=0"
            // We want x=\frac{a +/- b1\sqrt{b2}}{c}
            // where c=coeffs[0], a=-coeffs[1], b=coeffs[1]^2 -
            // 4*coeffs[0]*coeffs[2]
            int a = -coeffs[3];
            int b2 = coeffs[3] * coeffs[3] - 4 * coeffs[2] * coeffs[4];
            int b1 = 1;
            int c = 2 * coeffs[2];

            if (b2 <= 0) { // should not happen!
                appendUndefined(sb, tpl, num1);
                return;
            }

            // free the squares of b2
            while (b2 % 4 == 0) {
                b2 = b2 / 4;
                b1 = b1 * 2;
            }
            for (int s = 3; s <= Math.sqrt(b2); s += 2)
                while (b2 % (s * s) == 0) {
                    b2 = b2 / (s * s);
                    b1 = b1 * s;
                }

            if (c < 0) {
                a = -a;
                c = -c;
            }

            boolean positive;
            if (num1 > (a + 0.0) / c) {
                positive = true;
                if (b2 == 1) {
                    a += b1;
                    b1 = 0;
                    b2 = 0;
                }
            } else {
                positive = false;
                if (b2 == 1) {
                    a -= b1;
                    b1 = 0;
                    b2 = 0;
                }
            }

            int gcd = MathUtils.gcd(MathUtils.gcd(a, b1), c);
            if (gcd != 1) {
                a = a / gcd;
                b1 = b1 / gcd;
                c = c / gcd;
            }

            ExpressionNode en;

            if (Kernel.isZero(b1)) {
                // eg SurdText[0.33]
                // eg SurdText[0.235]
                en = new ExpressionNode(kernel, a);
            } else {
                en = (new ExpressionNode(kernel, b2)).sqrt().multiplyR(b1);

                if (positive) {
                    en = en.plusR(a);
                } else {
                    en = en.subtractR(a);
                }
            }

            en = en.divide(c);

            sb.append(en.toString(tpl));

        }
    } else if (coeffs[0] == 0) {
        sb.append("Root of a cubic equation: ");
        sb.append(kernel.format(coeffs[1], tpl));
        sb.append("x^3 + ");
        sb.append(kernel.format(coeffs[2], tpl));
        sb.append("x^2 + ");
        sb.append(kernel.format(coeffs[3], tpl));
        sb.append("x + ");
        sb.append(kernel.format(coeffs[4], tpl));

        // TODO: what to do in MathML?
        App.debug(sb.toString());
    } else {
        sb.append("Root of a quartic equation: ");
        sb.append(kernel.format(coeffs[0], tpl));
        sb.append("x^4 + ");
        sb.append(kernel.format(coeffs[1], tpl));
        sb.append("x^3 + ");
        sb.append(kernel.format(coeffs[2], tpl));
        sb.append("x^2 + ");
        sb.append(kernel.format(coeffs[3], tpl));
        sb.append("x + ");
        sb.append(kernel.format(coeffs[4], tpl));

        // TODO: what to do in MathML?
        App.debug(sb.toString());
    }

}

From source file:geogebra.common.kernel.cas.AlgoSurdText.java

/**
 * Quadratic Case. modifies a StringBuilder object sb to be the
 * quadratic-radical expression of num, within certain precision.
 * //from  w ww. j  av a2s. c  o m
 * @param sb
 * @param num1
 * @param tpl
 */
protected void PSLQappendQuadratic(StringBuilder sb, double num1, StringTemplate tpl) {

    if (Kernel.isZero(num1)) {
        DrawEquation.appendNumber(sb, tpl, "0");
        return;
    }

    double[] numPowers = { num1 * num1, num1, 1.0 };
    int[] coeffs = PSLQ(numPowers, 1E-10, 10);

    if (coeffs == null) {
        appendUndefined(sb, tpl, num1);
        return;
    }

    // debug0 = coeffs[0];
    // debug1 = coeffs[1];
    // debug2 = coeffs[2];

    // App.debug(coeffs[0]+" "+coeffs[1]+" "+coeffs[2]);
    if ((coeffs[0] == 0 && coeffs[1] == 0 && coeffs[2] == 0)

            // try to minimize possibility of wrong answer
            // and maximize usefulness
            // numbers determined by commented-out code in compute() method
            || Math.abs(coeffs[0]) > 570 || Math.abs(coeffs[1]) > 729 || Math.abs(coeffs[2]) > 465) {
        // App.debug(coeffs[0]+" "+coeffs[1]+" "+coeffs[2]);
        appendUndefined(sb, tpl, num1);
    } else if (coeffs[0] == 0) {
        // coeffs[1]: denominator; coeffs[2]: numerator
        int denom = coeffs[1];
        int numer = -coeffs[2];
        Fractionappend(sb, numer, denom, tpl);

    } else {

        // coeffs, if found, shows the equation
        // coeffs[2]+coeffs[1]x+coeffs[0]x^2=0"
        // We want x=\frac{a +/- b1\sqrt{b2}}{c}
        // where c=coeffs[0], a=-coeffs[1], b=coeffs[1]^2 -
        // 4*coeffs[0]*coeffs[2]
        int a = -coeffs[1];
        int b2 = coeffs[1] * coeffs[1] - 4 * coeffs[0] * coeffs[2];
        int b1 = 1;
        int c = 2 * coeffs[0];

        if (b2 <= 0) { // should not happen!
            appendUndefined(sb, tpl, num1);
            return;
        }

        // free the squares of b2
        while (b2 % 4 == 0) {
            b2 = b2 / 4;
            b1 = b1 * 2;
        }
        for (int s = 3; s <= Math.sqrt(b2); s += 2)
            while (b2 % (s * s) == 0) {
                b2 = b2 / (s * s);
                b1 = b1 * s;
            }

        if (c < 0) {
            a = -a;
            c = -c;
        }

        boolean positive;
        if (num1 > (a + 0.0) / c) {
            positive = true;
            if (b2 == 1) {
                a += b1;
                b1 = 0;
                b2 = 0;
            }
        } else {
            positive = false;
            if (b2 == 1) {
                a -= b1;
                b1 = 0;
                b2 = 0;
            }
        }

        int gcd = MathUtils.gcd(MathUtils.gcd(a, b1), c);
        if (gcd != 1) {
            a = a / gcd;
            b1 = b1 / gcd;
            c = c / gcd;
        }

        ExpressionNode en;
        if (Kernel.isZero(b1)) {
            // eg SurdText[0.33]
            // eg SurdText[0.235]
            en = new ExpressionNode(kernel, a);
        } else {
            en = (new ExpressionNode(kernel, b2)).sqrt().multiplyR(b1);

            if (positive) {
                en = en.plusR(a);
            } else {
                en = en.subtractR(a);
            }
        }
        en = en.divide(c);

        sb.append(en.toString(tpl));
    }

}

From source file:org.apache.flink.streaming.api.invokable.operator.BatchGroupReduceInvokable.java

public BatchGroupReduceInvokable(GroupReduceFunction<IN, OUT> reduceFunction, long batchSize, long slideSize) {
    super(reduceFunction);
    this.reducer = reduceFunction;
    this.batchSize = batchSize;
    this.slideSize = slideSize;
    this.granularity = (int) MathUtils.gcd(batchSize, slideSize);
    this.batchPerSlide = (int) (slideSize / granularity);
    this.numberOfBatches = batchSize / granularity;
    this.batch = new StreamBatch();
}

From source file:org.apache.flink.streaming.api.invokable.operator.BatchReduceInvokable.java

public BatchReduceInvokable(ReduceFunction<OUT> reduceFunction, long batchSize, long slideSize) {
    super(reduceFunction);
    this.reducer = reduceFunction;
    this.batchSize = batchSize;
    this.slideSize = slideSize;
    this.granularity = (int) MathUtils.gcd(batchSize, slideSize);
    this.batchPerSlide = slideSize / granularity;
    this.numberOfBatches = batchSize / granularity;
}