Example usage for java.math BigInteger multiply

List of usage examples for java.math BigInteger multiply

Introduction

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

Prototype

BigInteger multiply(long v) 

Source Link

Document

Package private methods used by BigDecimal code to multiply a BigInteger with a long.

Usage

From source file:nl.strohalm.cyclos.entities.ads.AdCategory.java

/**
 * returns a BigInteger indicating the global order index of the category. In the global order, whenever an item with children is encountered, all
 * child nodes are first handled before going on with the next item/node on the same level.<br>
 * Note that this method only works correctly with a maximum of 999 subcategories for a certain category.
 * @author rinke/*from  ww  w  .j a  v  a2s. com*/
 */
public BigInteger getGlobalOrder() {
    if (globalOrder == null) {
        final int correctedLevel = AdCategory.MAX_LEVEL - getLevel();
        final BigInteger levelFactor = new BigInteger("1000").pow(correctedLevel);
        // specified indexes are always > 0. Unspecified indexes of 0 mess up the calculation, so...
        final Integer index = (getOrder() == 0) ? 1 : getOrder();
        final BigInteger parentGlobalOrder = (getParent() == null) ? BigInteger.ZERO
                : getParent().getGlobalOrder();
        globalOrder = parentGlobalOrder.add(levelFactor.multiply(new BigInteger(index.toString())));
    }
    return globalOrder;
}

From source file:geogebra.kernel.AlgoBinomial.java

private double BinomBig(double n, double r) {
    if (r > n / 2)
        r = n - r;//  w  w w  . j av  a  2s. co  m
    BigInteger ncr = BigInteger.ONE, dd = BigInteger.ONE, nn, rr;
    //       nn=BigInteger.valueOf((long)n);
    //       rr=BigInteger.valueOf((long)r);

    // need a long-winded conversion in case n>10^18
    Double nnn = new Double(n);
    Double rrr = new Double(r);
    nn = (new BigDecimal(nnn.toString())).toBigInteger();
    rr = (new BigDecimal(rrr.toString())).toBigInteger();

    while (dd.compareTo(rr) <= 0) {
        ncr = ncr.multiply(nn);
        ncr = ncr.divide(dd); // dd is guaranteed to divide exactly into ncr here
        nn = nn.subtract(BigInteger.ONE);
        dd = dd.add(BigInteger.ONE);
    }
    return ncr.doubleValue();
}

From source file:it.nibbles.javacoin.block.BlockChainImpl.java

/**
 * Calculate the difficulty for the next block after the one supplied.
 *///from  w  w w. j av a  2  s .c  om
public DifficultyTarget getNextDifficultyTarget(BlockChainLink link, Block newBlock) {
    // If we're calculating for the genesis block return
    // fixed difficulty
    if (link == null)
        return bitcoinFactory.maxDifficultyTarget();
    // Look whether it's time to change the difficulty setting
    // (only change every TARGET_RECALC blocks). If not, return the
    // setting of this block, because the next one has to have the same
    // target.
    if ((link.getHeight() + 1) % TARGET_RECALC != 0) {
        // Special rules for testnet (for testnet2 only after 15 Feb 2012)
        Block currBlock = link.getBlock();
        if (bitcoinFactory.isTestnet3()
                || (bitcoinFactory.isTestnet2() && currBlock.getCreationTime() > 1329180000000L)) {
            // If the new block's timestamp is more than 2* 10 minutes
            // then allow mining of a min-difficulty block.
            if (newBlock.getCreationTime() > link.getBlock().getCreationTime() + 2 * TARGET_SPACING)
                return bitcoinFactory.maxDifficultyTarget();
            else {
                // Return the last non-special-min-difficulty-rules-block
                // We could use a custom method here to load only block headers instead of full blocks
                // but this lack of performance is only for the testnet so we don't care
                while (link != null && (link.getHeight() % TARGET_RECALC) != 0 && link.getBlock()
                        .getCompressedTarget() == bitcoinFactory.maxDifficultyTarget().getCompressedTarget())
                    link = linkStorage.getLinkBlockHeader(link.getBlock().getPreviousBlockHash());
                if (link != null)
                    return new DifficultyTarget(link.getBlock().getCompressedTarget());
                else
                    return bitcoinFactory.maxDifficultyTarget();
            }
        }
        logger.debug("previous height {}, not change in target", link.getHeight());
        return new DifficultyTarget(link.getBlock().getCompressedTarget());
    }
    // We have to change the target. First collect the last TARGET_RECALC 
    // blocks (including the given block) 
    Block startBlock = link.getBlock();
    for (int i = 0; (i < TARGET_RECALC - 1) && (startBlock != null); i++)
        startBlock = getBlockHeader(startBlock.getPreviousBlockHash());
    // This shouldn't happen, we reached genesis
    if (startBlock == null)
        return bitcoinFactory.maxDifficultyTarget();
    // Calculate the time the TARGET_RECALC blocks took
    long calculatedTimespan = link.getBlock().getCreationTime() - startBlock.getCreationTime();
    if (calculatedTimespan < TARGET_TIMESPAN / 4)
        calculatedTimespan = TARGET_TIMESPAN / 4;
    if (calculatedTimespan > TARGET_TIMESPAN * 4)
        calculatedTimespan = TARGET_TIMESPAN * 4;
    // Calculate new target, but allow no more than maximum target
    DifficultyTarget difficultyTarget = new DifficultyTarget(link.getBlock().getCompressedTarget());
    BigInteger target = difficultyTarget.getTarget();
    target = target.multiply(BigInteger.valueOf(calculatedTimespan));
    target = target.divide(BigInteger.valueOf(TARGET_TIMESPAN));
    // Return the new difficulty setting
    DifficultyTarget resultTarget = new DifficultyTarget(target);
    DifficultyTarget maxTarget = bitcoinFactory.maxDifficultyTarget();
    if (resultTarget.compareTo(maxTarget) > 0)
        return maxTarget;
    else
        resultTarget = new DifficultyTarget(resultTarget.getCompressedTarget()); // Normalize
    logger.debug("previous height {}, recalculated target is: {}", link.getHeight(), resultTarget);
    return resultTarget;
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private void stepTwoC() throws Exception {
    byte[] send;//from  w w w  . j  a  va 2 s .  com
    IHttpRequestResponse response;
    byte[] request;

    BigInteger n = this.pubKey.getModulus();

    loggerInstance.log(getClass(), "Step 2c: Searching with one interval left", Logger.LogLevel.INFO);

    // initial ri computation - ri = 2(b*(si-1)-2*B)/n
    BigInteger ri = this.si.multiply(this.m[0].upper);
    ri = ri.subtract(BigInteger.valueOf(2).multiply(this.bigB));
    ri = ri.multiply(BigInteger.valueOf(2));
    ri = ri.divide(n);

    // initial si computation
    BigInteger upperBound = step2cComputeUpperBound(ri, n, this.m[0].lower);
    BigInteger lowerBound = step2cComputeLowerBound(ri, n, this.m[0].upper);

    // to counter .add operation in do while
    this.si = lowerBound.subtract(BigInteger.ONE);

    do {
        // Check if user has cancelled the worker
        if (isCancelled()) {
            loggerInstance.log(getClass(), "Decryption Attack Executor Worker cancelled by user",
                    Logger.LogLevel.INFO);
            return;
        }

        this.si = this.si.add(BigInteger.ONE);
        // lowerBound <= si < upperBound
        if (this.si.compareTo(upperBound) > 0) {
            // new values
            ri = ri.add(BigInteger.ONE);
            upperBound = step2cComputeUpperBound(ri, n, this.m[0].lower);
            lowerBound = step2cComputeLowerBound(ri, n, this.m[0].upper);
            this.si = lowerBound;
        }
        send = prepareMsg(this.c0, this.si);

        request = this.requestResponse.getRequest();
        String[] components = Decoder.getComponents(this.parameter.getJoseValue());
        components[1] = Decoder.base64UrlEncode(send);

        String newComponentsConcatenated = Decoder.concatComponents(components);

        request = JoseParameter.updateRequest(request, this.parameter, helpers, newComponentsConcatenated);

        response = callbacks.makeHttpRequest(this.httpService, request);
        updateAmountRequest();

    } while (oracle.getResult(response.getResponse()) != BleichenbacherPkcs1Oracle.Result.VALID);
    loggerInstance.log(getClass(), "Matching response: " + helpers.bytesToString(response.getResponse()),
            Logger.LogLevel.DEBUG);
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private BigInteger step2cComputeLowerBound(final BigInteger r, final BigInteger modulus,
        final BigInteger upperIntervalBound) {
    BigInteger lowerBound = BigInteger.valueOf(2).multiply(this.bigB);
    lowerBound = lowerBound.add(r.multiply(modulus));
    lowerBound = lowerBound.divide(upperIntervalBound);

    return lowerBound;
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private BigInteger step2cComputeUpperBound(final BigInteger r, final BigInteger modulus,
        final BigInteger lowerIntervalBound) {
    BigInteger upperBound = BigInteger.valueOf(3).multiply(this.bigB);
    upperBound = upperBound.add(r.multiply(modulus));
    upperBound = upperBound.divide(lowerIntervalBound);

    return upperBound;
}

From source file:com.netflix.imfutility.cpl._2013.Cpl2013ContextBuilderStrategy.java

@Override
public BigFraction getCompositionTimecodeRate() {
    if (cpl2013.getCompositionTimecode() == null) {
        return null;
    }/* w w  w  .  ja va2s .c  om*/
    BigInteger rate = cpl2013.getCompositionTimecode().getTimecodeRate();
    boolean isDropFrame = cpl2013.getCompositionTimecode().isTimecodeDropFrame();
    if (rate == null || BigInteger.ZERO.equals(rate)) {
        return null;
    }

    // return as-is if non-drop
    if (!isDropFrame) {
        return new BigFraction(rate);
    }

    // return as 30000/1001 for 30 if drop frame
    return new BigFraction(rate.multiply(BigInteger.valueOf(1000)), BigInteger.valueOf(1001));
}

From source file:com.netflix.imfutility.cpl._2016.Cpl2016ContextBuilderStrategy.java

@Override
public BigFraction getCompositionTimecodeRate() {
    if (cpl2016.getCompositionTimecode() == null) {
        return null;
    }// w w  w  .j  a v  a 2s .c om
    BigInteger rate = cpl2016.getCompositionTimecode().getTimecodeRate();
    boolean isDropFrame = cpl2016.getCompositionTimecode().isTimecodeDropFrame();
    if (rate == null || BigInteger.ZERO.equals(rate)) {
        return null;
    }

    // return as-is if non-drop
    if (!isDropFrame) {
        return new BigFraction(rate);
    }

    // return as 30000/1001 for 30 if drop frame
    return new BigFraction(rate.multiply(BigInteger.valueOf(1000)), BigInteger.valueOf(1001));
}

From source file:com.chinamobile.bcbsp.util.Bytes.java

/**
 * Split passed range. Expensive operation relatively. Uses BigInteger math.
 * Useful splitting ranges for MapReduce jobs.
 *
 * @param a//from  w w w  .  j a va 2s.c  om
 *        Beginning of range
 * @param b
 *        End of range
 * @param num
 *        Number of times to split range. Pass 1 if you want to split the
 *        range in two; i.e. one split.
 * @return Array of dividing values
 */
public static byte[][] split(final byte[] a, final byte[] b, final int num) {
    byte[] aPadded;
    byte[] bPadded;
    if (a.length < b.length) {
        aPadded = padTail(a, b.length - a.length);
        bPadded = b;
    } else if (b.length < a.length) {
        aPadded = a;
        bPadded = padTail(b, a.length - b.length);
    } else {
        aPadded = a;
        bPadded = b;
    }
    if (compareTo(aPadded, bPadded) >= 0) {
        throw new IllegalArgumentException("b <= a");
    }
    if (num <= 0) {
        throw new IllegalArgumentException("num cannot be < 0");
    }
    byte[] prependHeader = { 1, 0 };
    BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
    BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
    BigInteger diffBI = stopBI.subtract(startBI);
    BigInteger splitsBI = BigInteger.valueOf(num + 1);
    if (diffBI.compareTo(splitsBI) < 0) {
        return null;
    }
    BigInteger intervalBI;
    try {
        intervalBI = diffBI.divide(splitsBI);
    } catch (Exception e) {
        LOG.error("Exception caught during division", e);
        return null;
    }
    byte[][] result = new byte[num + 2][];
    result[0] = a;
    for (int i = 1; i <= num; i++) {
        BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i)));
        byte[] padded = curBI.toByteArray();
        if (padded[1] == 0) {
            padded = tail(padded, padded.length - 2);
        } else {
            padded = tail(padded, padded.length - 1);
        }
        result[i] = padded;
    }
    result[num + 1] = b;
    return result;
}

From source file:org.jbpm.formModeler.core.processing.formRendering.FormRenderingFormatter.java

protected BigInteger calculateMCM(List colspans) {
    if (colspans == null || colspans.isEmpty()) {
        return new BigInteger("1");
    } else if (colspans.size() == 1) {
        return (BigInteger) colspans.get(0);
    } else if (colspans.size() == 2) {
        BigInteger b1 = (BigInteger) colspans.get(0);
        BigInteger b2 = (BigInteger) colspans.get(1);
        return b1.multiply(b2).divide(b1.gcd(b2));
    } else { //Size > 2
        int halfLength = colspans.size() / 2;
        List firstHalf = colspans.subList(0, halfLength);
        List secondHalf = colspans.subList(halfLength, colspans.size());
        BigInteger b1 = calculateMCM(firstHalf);
        BigInteger b2 = calculateMCM(secondHalf);
        return b1.multiply(b2).divide(b1.gcd(b2));
    }//from  ww w.  ja v a  2 s .  c o  m
}