Example usage for java.math BigInteger ONE

List of usage examples for java.math BigInteger ONE

Introduction

In this page you can find the example usage for java.math BigInteger ONE.

Prototype

BigInteger ONE

To view the source code for java.math BigInteger ONE.

Click Source Link

Document

The BigInteger constant one.

Usage

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

@Override
public int init(int newPin, SystemParameters pseuParams, RSAKeyPair rootKey, short deviceId) {
    if (this.wasInit()) {
        return -1;
    }/*from w  w  w.j  a v  a  2  s  .c om*/
    try {

        byte[] deviceID = ByteBuffer.allocate(2).putShort(deviceId).array();
        this.setAuthenticationKey(rootKey.getN(), 0, null);
        byte[] deviceKeySize = this.intLengthToShortByteArr(pseuParams.deviceSecretSizeBytes);
        byte[] idAndDeviceKeySize = new byte[] { deviceID[0], deviceID[1], deviceKeySize[0], deviceKeySize[1] };
        ByteBuffer buf = ByteBuffer.allocate(13);
        buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.initializeDevice, 0, 0, 0, 0, 4 });
        buf.put(idAndDeviceKeySize);
        buf.put(new byte[] { 0, 0 });
        buf.position(0);
        if (printInput)
            System.out.println("Input to initialize device: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
            return -1;
        }
        byte[] pinAndPuk = SmartcardCrypto.decrypt(response.getData(), rootKey);
        byte[] pin = new byte[4];
        byte[] puk = new byte[8];
        System.arraycopy(pinAndPuk, 0, pin, 0, 4);
        System.arraycopy(pinAndPuk, 4, puk, 0, 8);
        String ipin = "", ipuk = "";
        for (int i = 0; i < 4; i++) {
            ipin += (char) (pin[i] & 0xFF);
        }
        for (int i = 0; i < 8; i++) {
            ipuk += (char) (puk[i] & 0xFF);
        }
        if (this.changePin(Integer.parseInt(ipin), newPin) != SmartcardStatusCode.OK) {
            System.out.println("Could not change pin.");
            return -1;
        }

        System.out.println("Now initializing group stuff");
        int mode = this.getMode();

        if (this.setGroupComponent(mode, pseuParams.p.toByteArray(), 0, 0, null) != SmartcardStatusCode.OK) {
            return -1;
        }
        if (this.setGroupComponent(mode, pseuParams.subgroupOrder.toByteArray(), 0, 1,
                null) != SmartcardStatusCode.OK) {
            return -1;
        }
        BigInteger f = pseuParams.p.subtract(BigInteger.ONE).divide(pseuParams.subgroupOrder); //cofactor
        this.setGroupComponent(mode, f.toByteArray(), 0, 2, null);

        //then add a generator of the subgroup q
        if (this.setGenerator(mode, pseuParams.g.toByteArray(), 0, 1, null) != SmartcardStatusCode.OK) {
            return -1;
        }

        //set prover
        byte[] data = new byte[5 + MAX_CREDENTIALS + 1];
        data[0] = 1; //id 1
        int ksize = pseuParams.zkChallengeSizeBytes * 2 + pseuParams.zkStatisticalHidingSizeBytes;
        byte[] ksize_bytes = this.intLengthToShortByteArr(ksize);
        data[1] = ksize_bytes[0];
        data[2] = ksize_bytes[1]; // as large as the subgroup order is -1 to prevent overflow.
        int csize = pseuParams.zkChallengeSizeBytes;
        byte[] csize_bytes = this.intLengthToShortByteArr(csize);
        data[3] = csize_bytes[0];
        data[4] = csize_bytes[1]; // challenge size: 256 bit = 32 bytes (as per default in SystemParameters)
        for (int i = 0; i <= MAX_CREDENTIALS; i++) {
            //0 means it accepts both credentials and scope-exclusive stuff.
            //1,2,3,... means it accepts credentials with id 1,2,3,...
            data[i + 5] = (byte) i;
        }
        buf = ByteBuffer.allocate(5 + data.length);
        buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.setProver, 0, 0, (byte) data.length });
        buf.put(data);
        buf.position(0);
        System.out.println("Input to prover: " + Arrays.toString(buf.array()));
        response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from setProver: " + response);
        if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
            return -1;
        }

        //After init, one should call setIssuer which creates a group and counter.
        return Integer.parseInt(ipuk);
    } catch (CardException e) {
        e.printStackTrace();
        return -1;
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Riemann zeta function./* ww  w  .j a  v  a  2s.c o m*/
 *
 * @param n  The positive integer argument.
 *           32
 * @param mc Specification of the accuracy of the result.
 * @return zeta(n).
 */
static public BigDecimal zeta(final int n, final MathContext mc) {
    if (n <= 0) {
        throw new ProviderException("Unimplemented zeta at negative argument " + n);
    }

    if (n == 1) {
        throw new ArithmeticException("Pole at zeta(1) ");
    }

    if (n % 2 == 0) {
        /* Even indices. Abramowitz-Stegun 23.2.16. Start with 2^(n-1)*B(n)/n!
         */
        Rational b = (new Bernoulli()).at(n).abs();
        b = b.divide((new Factorial()).at(n));
        b = b.multiply(BigInteger.ONE.shiftLeft(n - 1));
        /* to be multiplied by pi^n. Absolute error in the result of pi^n is n times
         * error in pi times pi^(n-1). Relative error is n*error(pi)/pi, requested by mc.
         * Need one more digit in pi if n=10, two digits if n=100 etc, and add one extra digit.
         */
        MathContext mcpi = new MathContext(mc.getPrecision() + (int) (Math.log10(10.0 * n)));
        final BigDecimal piton = pi(mcpi).pow(n, mc);

        return multiplyRound(piton, b);

    } else if (n == 3) {
        /* Broadhurst BBP \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}
         * Error propagation: S31 is roughly 0.087, S33 roughly 0.131
         */
        int[] a31 = { 1, -7, -1, 10, -1, -7, 1, 0 };

        int[] a33 = { 1, 1, -1, -2, -1, 1, 1, 0 };
        BigDecimal S31 = broadhurstBBP(3, 1, a31, mc);
        BigDecimal S33 = broadhurstBBP(3, 3, a33, mc);
        S31 = S31.multiply(new BigDecimal(48));
        S33 = S33.multiply(new BigDecimal(32));

        return S31.add(S33).divide(new BigDecimal(7), mc);

    } else if (n == 5) {
        /* Broadhurst BBP \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}
         * Error propagation: S51 is roughly -11.15, S53 roughly 22.165, S55 is roughly 0.031
         * 9*2048*S51/6265 = -3.28. 7*2038*S53/61651= 5.07. 738*2048*S55/61651= 0.747.
         * The result is of the order 1.03, so we add 2 digits to S51 and S52 and one digit to S55.
         */
        int[] a51 = { 31, -1614, -31, -6212, -31, -1614, 31, 74552 };

        int[] a53 = { 173, 284, -173, -457, -173, 284, 173, -111 };

        int[] a55 = { 1, 0, -1, -1, -1, 0, 1, 1 };
        BigDecimal S51 = broadhurstBBP(5, 1, a51, new MathContext(2 + mc.getPrecision()));
        BigDecimal S53 = broadhurstBBP(5, 3, a53, new MathContext(2 + mc.getPrecision()));
        BigDecimal S55 = broadhurstBBP(5, 5, a55, new MathContext(1 + mc.getPrecision()));
        S51 = S51.multiply(new BigDecimal(18432));
        S53 = S53.multiply(new BigDecimal(14336));
        S55 = S55.multiply(new BigDecimal(1511424));

        return S51.add(S53).subtract(S55).divide(new BigDecimal(62651), mc);

    } else {
        /* Cohen et al Exp Math 1 (1) (1992) 25
         */
        Rational betsum = new Rational();
        Bernoulli bern = new Bernoulli();
        Factorial fact = new Factorial();

        for (int npr = 0; npr <= (n + 1) / 2; npr++) {
            Rational b = bern.at(2 * npr).multiply(bern.at(n + 1 - 2 * npr));
            b = b.divide(fact.at(2 * npr)).divide(fact.at(n + 1 - 2 * npr));
            b = b.multiply(1 - 2 * npr);

            if (npr % 2 == 0) {
                betsum = betsum.add(b);
            } else {
                betsum = betsum.subtract(b);
            }

        }
        betsum = betsum.divide(n - 1);
        /* The first term, including the facor (2pi)^n, is essentially most
         * of the result, near one. The second term below is roughly in the range 0.003 to 0.009.
         * So the precision here is matching the precisionn requested by mc, and the precision
         * requested for 2*pi is in absolute terms adjusted.
         */
        MathContext mcloc = new MathContext(2 + mc.getPrecision() + (int) (Math.log10((double) (n))));
        BigDecimal ftrm = pi(mcloc).multiply(new BigDecimal(2));
        ftrm = ftrm.pow(n);

        ftrm = multiplyRound(ftrm, betsum.BigDecimalValue(mcloc));
        BigDecimal exps = new BigDecimal(0);
        /* the basic accuracy of the accumulated terms before multiplication with 2
         */

        double eps = Math.pow(10., -mc.getPrecision());

        if (n % 4 == 3) {
            /* since the argument n is at least 7 here, the drop
             * of the terms is at rather constant pace at least 10^-3, for example
             * 0.0018, 0.2e-7, 0.29e-11, 0.74e-15 etc for npr=1,2,3.... We want 2 times these terms
             * fall below eps/10.
             */
            int kmax = mc.getPrecision() / 3;
            eps /= kmax;
            /* need an error of eps for 2/(exp(2pi)-1) = 0.0037
             * The absolute error is 4*exp(2pi)*err(pi)/(exp(2pi)-1)^2=0.0075*err(pi)
             */
            BigDecimal exp2p = pi(new MathContext(3 + err2prec(3.14, eps / 0.0075)));
            exp2p = exp(exp2p.multiply(new BigDecimal(2)));
            BigDecimal c = exp2p.subtract(BigDecimal.ONE);
            exps = divideRound(1, c);

            for (int npr = 2; npr <= kmax; npr++) {
                /* the error estimate above for npr=1 is the worst case of
                 * the absolute error created by an error in 2pi. So we can
                 * safely re-use the exp2p value computed above without
                 * reassessment of its error.
                 */
                c = powRound(exp2p, npr).subtract(BigDecimal.ONE);
                c = multiplyRound(c, (new BigInteger("" + npr)).pow(n));
                c = divideRound(1, c);
                exps = exps.add(c);

            }
        } else {
            /* since the argument n is at least 9 here, the drop
             * of the terms is at rather constant pace at least 10^-3, for example
             * 0.0096, 0.5e-7, 0.3e-11, 0.6e-15 etc. We want these terms
             * fall below eps/10.
             */
            int kmax = (1 + mc.getPrecision()) / 3;
            eps /= kmax;
            /* need an error of eps for 2/(exp(2pi)-1)*(1+4*Pi/8/(1-exp(-2pi)) = 0.0096
             * at k=7 or = 0.00766 at k=13 for example.
             * The absolute error is 0.017*err(pi) at k=9, 0.013*err(pi) at k=13, 0.012 at k=17
             */
            BigDecimal twop = pi(new MathContext(3 + err2prec(3.14, eps / 0.017)));
            twop = twop.multiply(new BigDecimal(2));
            BigDecimal exp2p = exp(twop);
            BigDecimal c = exp2p.subtract(BigDecimal.ONE);
            exps = divideRound(1, c);
            c = BigDecimal.ONE.subtract(divideRound(1, exp2p));
            c = divideRound(twop, c).multiply(new BigDecimal(2));
            c = divideRound(c, n - 1).add(BigDecimal.ONE);
            exps = multiplyRound(exps, c);

            for (int npr = 2; npr <= kmax; npr++) {
                c = powRound(exp2p, npr).subtract(BigDecimal.ONE);
                c = multiplyRound(c, (new BigInteger("" + npr)).pow(n));
                BigDecimal d = divideRound(1, exp2p.pow(npr));
                d = BigDecimal.ONE.subtract(d);
                d = divideRound(twop, d).multiply(new BigDecimal(2 * npr));
                d = divideRound(d, n - 1).add(BigDecimal.ONE);
                d = divideRound(d, c);
                exps = exps.add(d);

            }
        }
        exps = exps.multiply(new BigDecimal(2));

        return ftrm.subtract(exps, mc);

    }
}

From source file:com.farouk.projectapp.FirstGUI.java

private void jButton19ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton19ActionPerformed

    if (StringThirdParty.equals("")) {
        JOptionPane.showMessageDialog(rootPane, "Please select a company first.", "Oo-Ohh", WIDTH);
    } else if (SQLConnect.ifAutomated(userID, StringThirdParty) == 2) {
        SQLConnect.removeAutomation(userID, StringThirdParty);
    } else {//from   ww w  . j a  va2 s  .c  o m
        String aux = jTextField4.getText();
        try {
            BigDecimal price = new BigDecimal(jTextField4.getText());
            if (price.compareTo(BigDecimal.ZERO) == 1) {
                if (jTextField4.getText().isEmpty()) {
                    JOptionPane.showMessageDialog(rootPane, "Please enter a valid input.", "Error", WIDTH);
                } else {
                    String symb = SQLConnect.getSymbolOfCompanyFromDB(StringThirdParty);

                    SQLConnect.saveAutomateSettings(userID, symb, new BigDecimal(BigInteger.ONE), price, 0, 0,
                            0);

                }
            } else {
                JOptionPane.showMessageDialog(rootPane, "Enter a positive number.", "No !", WIDTH);
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(rootPane, "Please provide a valid number", "Bad input", WIDTH);
        }

    }

}

From source file:edu.hku.sdb.rewrite.SdbSchemeRewriter.java

/**
 * Do keyUpdate for a plain text column.
 *
 * @param P/*from w  w  w.  j  av  a 2s  .  c om*/
 * @param S
 * @param targetM
 * @param targetX
 * @return
 */
private Expr keyUpdatePlainCol(Expr P, Expr S, BigInteger targetM, BigInteger targetX) {
    LOG.debug("Building key update expression for plain column" + P.toSql());
    BigInteger pM = BigInteger.ONE;
    BigInteger pX = BigInteger.ZERO;

    BigInteger[] pq = SDBEncrypt.keyUpdateClient(pM, targetM, S.getSdbColKey().getM(), pX, targetX,
            S.getSdbColKey().getX(), prime1, prime2);

    return buildSdbKeyUpdateExpr(P, S, new BigIntLiteral(pq[0]), new BigIntLiteral(pq[1]), new BigIntLiteral(n),
            targetM, targetX);

}

From source file:edu.hku.sdb.rewrite.SdbSchemeRewriter.java

/**
 * Do keyUpdate for a plain text column but inverse its value.
 *
 * @param P/*from   w  w w.j  a va2 s .  c o  m*/
 * @param S
 * @param targetM
 * @param targetX
 * @return
 */
private Expr keyUpdateInversedPlainCol(Expr P, Expr S, BigInteger targetM, BigInteger targetX) {
    LOG.debug("Building key update inverse expression for plain column" + P.toSql());

    BigInteger pM = n.subtract(BigInteger.ONE);
    BigInteger pX = BigInteger.ZERO;

    BigInteger[] pq = SDBEncrypt.keyUpdateClient(pM, targetM, S.getSdbColKey().getM(), pX, targetX,
            S.getSdbColKey().getX(), prime1, prime2);

    return buildSdbKeyUpdateExpr(P, S, new BigIntLiteral(pq[0]), new BigIntLiteral(pq[1]), new BigIntLiteral(n),
            targetM, targetX);

}

From source file:net.pms.util.Rational.java

/**
 * Calculates the greatest common divisor for two {@link BigInteger}s using
 * {@link BigInteger#gcd}.//from www.j a v  a 2s .  c om
 *
 * @param u the first number.
 * @param v the second number.
 * @return The GDC, always 1 or greater.
 */
@Nullable
public static BigInteger calculateGreatestCommonDivisor(@Nullable BigInteger u, @Nullable BigInteger v) {
    if (u == null || v == null) {
        return null;
    }
    if (u.abs().compareTo(BigInteger.ONE) <= 0 || v.abs().compareTo(BigInteger.ONE) <= 0) {
        return BigInteger.ONE;
    }
    return u.gcd(v);
}

From source file:net.pms.util.Rational.java

/**
 * Calculates the least common multiple for two {@link BigInteger}s using the formula
 * {@code u * v / gcd(u, v)} where {@code gcd} is the greatest common divisor for the two.
 *
 * @param u the first number.//from w w  w  .  ja  v  a  2s  . co  m
 * @param v the second number.
 * @return The LCM, always 1 or greater.
 */
@Nullable
public static BigInteger calculateLeastCommonMultiple(@Nullable BigInteger u, @Nullable BigInteger v) {
    if (u == null || v == null) {
        return null;
    }
    if (u.signum() == 0 && v.signum() == 0) {
        return BigInteger.ONE;
    }
    u = u.abs();
    v = v.abs();
    if (u.signum() == 0) {
        return v;
    }
    if (v.signum() == 0) {
        return u;
    }
    return u.divide(calculateGreatestCommonDivisor(u, v)).multiply(v);
}

From source file:edu.hku.sdb.rewrite.SdbSchemeRewriter.java

/**
 * TODO: We assume the predicate cannot have columns from different table.
 *
 * @param normalBinPred//from  w  w w  .j a  v  a 2  s .c  o  m
 * @param R
 * @param S
 * @return
 * @throws UnSupportedException
 */
protected Expr rewriteNorBinPredicate(NormalBinPredicate normalBinPred, Expr R, Expr S)
        throws UnSupportedException {
    LOG.debug("Rewriting normal binary predicate " + normalBinPred.toSql());

    // No SDB encrypted column.
    if (!normalBinPred.involveEncrytedCol())
        return normalBinPred;

    Expr leftExpr = normalBinPred.getLeftExpr();
    Expr rightExpr = normalBinPred.getRightExpr();

    Expr subtractExpr;
    Expr multiplyExpr;

    BigInteger targetM = BigInteger.ONE;
    BigInteger targetX = BigInteger.ZERO;

    Expr keyUpdateExpr = null;
    Expr compareExpr = new SdbComparisonExpr(normalBinPred.getOp());

    // EE mode
    if (leftExpr.involveEncrytedCol() && rightExpr.involveEncrytedCol()) {
        if (leftExpr instanceof NormalArithmeticExpr) {
            leftExpr = rewriteNorArithExpr((NormalArithmeticExpr) leftExpr, S);
        }

        if (rightExpr instanceof NormalArithmeticExpr) {
            rightExpr = rewriteNorArithExpr((NormalArithmeticExpr) rightExpr, S);
        }

        subtractExpr = rewriteSubtractEE(leftExpr, rightExpr, S);
        multiplyExpr = rewriteMultiplyEE(R, subtractExpr);

        BigInteger[] pq = SDBEncrypt.keyUpdateClient(multiplyExpr.getSdbColKey().getM(), targetM,
                S.getSdbColKey().getM(), multiplyExpr.getSdbColKey().getX(), targetX, S.getSdbColKey().getX(),
                prime1, prime2);

        keyUpdateExpr = buildSdbKeyUpdateExpr(multiplyExpr, S, new BigIntLiteral(pq[0]),
                new BigIntLiteral(pq[1]), new BigIntLiteral(n), targetM, targetX);

    } else if (leftExpr.involveEncrytedCol() || rightExpr.involveEncrytedCol()) {
        // EC mode

        if (leftExpr instanceof IntLiteral || leftExpr instanceof FloatLiteral
                || rightExpr instanceof IntLiteral || rightExpr instanceof FloatLiteral) {
            if (leftExpr instanceof NormalArithmeticExpr) {
                leftExpr = rewriteNorArithExpr((NormalArithmeticExpr) leftExpr, S);
            }

            if (rightExpr instanceof NormalArithmeticExpr) {
                rightExpr = rewriteNorArithExpr((NormalArithmeticExpr) rightExpr, S);
            }

            subtractExpr = rewriteSubtractEC(leftExpr, rightExpr, S);
            multiplyExpr = rewriteMultiplyEE(R, subtractExpr);

            BigInteger[] pq = SDBEncrypt.keyUpdateClient(multiplyExpr.getSdbColKey().getM(), targetM,
                    S.getSdbColKey().getM(), multiplyExpr.getSdbColKey().getX(), targetX,
                    S.getSdbColKey().getX(), prime1, prime2);

            keyUpdateExpr = buildSdbKeyUpdateExpr(multiplyExpr, S, new BigIntLiteral(pq[0]),
                    new BigIntLiteral(pq[1]), new BigIntLiteral(n), targetM, targetX);
        }

        // EP mode
        else if (leftExpr instanceof FieldLiteral || rightExpr instanceof FieldLiteral) {
            if (leftExpr instanceof NormalArithmeticExpr) {
                leftExpr = rewriteNorArithExpr((NormalArithmeticExpr) leftExpr, S);
            }

            if (rightExpr instanceof NormalArithmeticExpr) {
                rightExpr = rewriteNorArithExpr((NormalArithmeticExpr) rightExpr, S);
            }

            subtractExpr = rewriteSubtractEP(leftExpr, rightExpr, S);
            multiplyExpr = rewriteMultiplyEE(R, subtractExpr);

            BigInteger[] pq = SDBEncrypt.keyUpdateClient(multiplyExpr.getSdbColKey().getM(), targetM,
                    S.getSdbColKey().getM(), multiplyExpr.getSdbColKey().getX(), targetX,
                    S.getSdbColKey().getX(), prime1, prime2);

            keyUpdateExpr = buildSdbKeyUpdateExpr(multiplyExpr, S, new BigIntLiteral(pq[0]),
                    new BigIntLiteral(pq[1]), new BigIntLiteral(n), targetM, targetX);
        }
    }

    if (normalBinPred.getOp() != BinaryPredicate.BinOperator.EQ) {
        compareExpr.addChild(keyUpdateExpr);
        compareExpr.addChild(new BigIntLiteral(n.subtract(BigInteger.ONE).divide(new BigInteger("2"))));
    } else {
        compareExpr.addChild(keyUpdateExpr);
    }

    return compareExpr;
}

From source file:net.pms.util.Rational.java

/**
 * Used internally to generate a hexadecimal rational string representation
 * from two {@link BigInteger}s.//from  www. java  2s  .c o  m
 *
 * @param numerator the numerator.
 * @param denominator the denominator.
 * @return The hexadecimal rational string representation.
 */
@Nonnull
protected static String generateRationalHexString(@Nonnull BigInteger numerator,
        @Nonnull BigInteger denominator) {
    if (denominator.signum() == 0) {
        if (numerator.signum() == 0) {
            return "NaN";
        }
        return numerator.signum() > 0 ? "\u221e" : "-\u221e";
    }
    if (BigInteger.ONE.equals(denominator)) {
        return numerator.toString(16);
    }
    return numerator.toString(16) + "/" + denominator.toString(16);
}

From source file:net.pms.util.Rational.java

/**
 * Used internally to generate a rational string representation from two
 * {@link BigInteger}s.//  ww  w.  j  ava 2s .c  om
 *
 * @param numerator the numerator.
 * @param denominator the denominator.
 * @return The rational string representation.
 */
@Nonnull
protected static String generateRationalString(@Nonnull BigInteger numerator, @Nonnull BigInteger denominator) {
    if (denominator.signum() == 0) {
        if (numerator.signum() == 0) {
            return "NaN";
        }
        return numerator.signum() > 0 ? "\u221e" : "-\u221e";
    }
    if (BigInteger.ONE.equals(denominator)) {
        return numerator.toString();
    }
    return numerator.toString() + "/" + denominator.toString();
}