Example usage for java.math BigInteger divide

List of usage examples for java.math BigInteger divide

Introduction

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

Prototype

public BigInteger divide(BigInteger val) 

Source Link

Document

Returns a BigInteger whose value is (this / val) .

Usage

From source file:org.limewire.mojito.util.DHTSizeEstimator.java

/**
 * Computes and returns the approximate DHT size based 
 * on the given List of Contacts.//from www .ja va2 s  .co m
 */
public synchronized BigInteger computeSize(Collection<? extends Contact> nodes) {

    // Works only with more than two Nodes
    if (nodes.size() < MIN_NODE_COUNT) {
        // There's always us!
        return BigInteger.ONE.max(BigInteger.valueOf(nodes.size()));
    }

    // Get the Iterator. We assume the Contacts are sorted by
    // their xor distance!
    Iterator<? extends Contact> contacts = nodes.iterator();

    // See Azureus DHTControlImpl.estimateDHTSize()
    // Di = nearestId xor NodeIDi
    // Dc = sum(i * Di) / sum(i * i)
    // Size = 2**160 / Dc

    BigInteger sum1 = BigInteger.ZERO;
    BigInteger sum2 = BigInteger.ZERO;

    // The algorithm works relative to the ID space.
    KUID nearestId = contacts.next().getNodeID();

    // We start 1 because the nearest Node is the 0th item!
    for (int i = 1; contacts.hasNext(); i++) {
        Contact node = contacts.next();

        BigInteger distance = nearestId.xor(node.getNodeID()).toBigInteger();
        BigInteger j = BigInteger.valueOf(i);

        sum1 = sum1.add(j.multiply(distance));
        sum2 = sum2.add(j.pow(2));
    }

    BigInteger estimatedSize = BigInteger.ZERO;
    if (!sum1.equals(BigInteger.ZERO)) {
        estimatedSize = KUID.MAXIMUM.toBigInteger().multiply(sum2).divide(sum1);
    }

    // And there is always us!
    estimatedSize = BigInteger.ONE.max(estimatedSize);

    // Get the average of the local estimations
    BigInteger localSize = BigInteger.ZERO;
    localSizeHistory.add(estimatedSize);

    // Adjust the size of the List. The Setting is SIMPP-able
    // and may change!
    int maxLocalHistorySize = ContextSettings.MAX_LOCAL_HISTORY_SIZE.getValue();
    while (localSizeHistory.size() > maxLocalHistorySize && !localSizeHistory.isEmpty()) {
        localSizeHistory.remove(0);
    }

    if (!localSizeHistory.isEmpty()) {
        BigInteger localSizeSum = BigInteger.ZERO;
        for (BigInteger size : localSizeHistory) {
            localSizeSum = localSizeSum.add(size);
        }

        localSize = localSizeSum.divide(BigInteger.valueOf(localSizeHistory.size()));
    }

    // Get the combined average
    // S = (localEstimation + sum(remoteEstimation[i]))/count
    BigInteger combinedSize = localSize;
    if (ContextSettings.COUNT_REMOTE_SIZE.getValue()) {
        // Prune all duplicates and sort the values
        Set<BigInteger> remoteSizeSet = new TreeSet<BigInteger>(remoteSizeHistory);

        if (remoteSizeSet.size() >= 3) {
            BigInteger[] remote = remoteSizeSet.toArray(new BigInteger[0]);

            // Skip the smallest and largest values
            int count = 1;
            int skip = ContextSettings.SKIP_REMOTE_ESTIMATES.getValue();
            for (int i = skip; (skip >= 0) && (i < (remote.length - skip)); i++) {
                combinedSize = combinedSize.add(remote[i]);
                count++;
            }
            combinedSize = combinedSize.divide(BigInteger.valueOf(count));

            // Make sure we didn't exceed the MAXIMUM number as
            // we made an addition with the local estimation which
            // might be already 2**160 bit!
            combinedSize = combinedSize.min(MAXIMUM);
        }
    }

    // There is always us!
    return BigInteger.ONE.max(combinedSize);
}

From source file:com.spotify.hdfs2cass.cassandra.utils.CassandraPartitioner.java

@Override
public int getPartition(AvroKey<ByteBuffer> key, AvroValue<Mutation> value, int numReducers) {
    if (distributeRandomly) {
        return reducers.get(random.nextInt(reducers.size()));
    }//from www  .  ja va2  s . c o m

    final Token token = partitioner.getToken(key.datum());
    BigInteger bigIntToken;
    if (token instanceof BigIntegerToken) {
        bigIntToken = ((BigIntegerToken) token).token.abs();
    } else if (token instanceof LongToken) {
        bigIntToken = BigInteger.valueOf(((LongToken) token).token).add(MURMUR3_SCALE);
    } else {
        throw new RuntimeException(
                "Invalid partitioner Token type. Only BigIntegerToken and LongToken supported");
    }
    return reducers.get(bigIntToken.divide(rangePerReducer).intValue());
}

From source file:org.owasp.jbrofuzz.core.FuzzerBigInteger.java

/**
 * <p>Return the next element of the fuzzer during iteration.</p>
 * /* ww  w  .  j a v a  2s.c  o m*/
 * <p>This method should be used to access fuzzing payloads, after
 * construction of the fuzzer object.</p>
 * 
 * @return String   The next fuzzer payload, during the iteration 
 *                process
 * 
 * @author subere@uncon.org
 * @version 2.4
 * @since 1.2
 */
public String next() {

    final StringBuffer output = new StringBuffer("");

    // Replacive Prototype
    if (maxValue.compareTo(BigInteger.valueOf(payloads.size())) == 0) {

        output.append(payloads.get(cValue.intValue()));
        cValue = cValue.add(BigInteger.ONE);

    }
    // Recursive Prototype
    else {

        BigInteger val = cValue;
        // Perform division on a stack
        final Stack<BigInteger> stack = new Stack<BigInteger>();
        while (val.compareTo(BigInteger.valueOf(payloads.size())) >= 0) {

            stack.push(val.mod(BigInteger.valueOf(payloads.size())));
            val = val.divide(BigInteger.valueOf(payloads.size()));

        }
        // Append the relevant empty positions with the first element
        // identified
        output.append(StringUtils.leftPad(payloads.get(val.intValue()), len - stack.size(), payloads.get(0)));
        while (!stack.isEmpty()) {
            output.append(payloads.get(stack.pop().intValue()));
        }

        cValue = cValue.add(BigInteger.ONE);

    }

    return output.toString();

}

From source file:de.jfachwert.math.Bruch.java

/**
 * Liefert einen gekuerzten Bruch zurueck. So wird z.B. der Bruch "2/4" als
 * "1/2" zurueckgegeben.//from   www .  j  a v a 2 s . c o m
 *
 * @return gekuerzter Bruch
 */
public Bruch kuerzen() {
    BigInteger z = getZaehler();
    BigInteger n = getNenner();
    for (Primzahl p = Primzahl.first(); p.toBigInteger().compareTo(n) < 0; p = p.next()) {
        BigInteger teiler = p.toBigInteger();
        while (z.mod(teiler).equals(BigInteger.ZERO) && (n.mod(teiler).equals(BigInteger.ZERO))) {
            z = z.divide(teiler);
            n = n.divide(teiler);
        }
    }
    return Bruch.of(z, n);
}

From source file:org.apache.accumulo.pig.Bytes.java

/**
 * Iterate over keys within the passed inclusive range.
 *//*from  w w  w  .java 2s .  c o  m*/
public static Iterable<byte[]> iterateOnSplits(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 };
    final BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
    final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
    final BigInteger diffBI = stopBI.subtract(startBI);
    final BigInteger splitsBI = BigInteger.valueOf(num + 1);
    if (diffBI.compareTo(splitsBI) < 0) {
        return null;
    }
    final BigInteger intervalBI;
    try {
        intervalBI = diffBI.divide(splitsBI);
    } catch (Exception e) {
        LOG.error("Exception caught during division", e);
        return null;
    }

    final Iterator<byte[]> iterator = new Iterator<byte[]>() {
        private int i = -1;

        @Override
        public boolean hasNext() {
            return i < num + 1;
        }

        @Override
        public byte[] next() {
            i++;
            if (i == 0) {
                return a;
            }
            if (i == num + 1) {
                return b;
            }

            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);
            }
            return padded;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };

    return new Iterable<byte[]>() {
        @Override
        public Iterator<byte[]> iterator() {
            return iterator;
        }
    };
}

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:burstcoin.observer.service.AssetService.java

private String convertPrice(String priceString, int decimals) {
    BigInteger price = new BigInteger(priceString);
    BigInteger amount = price.multiply(new BigInteger("" + (long) Math.pow(10, decimals)));
    String negative = "";
    String afterComma = "";
    String fractionalPart = amount.mod(new BigInteger("100000000")).toString();
    amount = amount.divide(new BigInteger("100000000"));
    if (amount.compareTo(BigInteger.ZERO) < 0) {
        amount = amount.abs();//from  w  w w . ja  v a2  s  . com
        negative = "-";
    }
    if (!fractionalPart.equals("0")) {
        afterComma = ".";
        for (int i = fractionalPart.length(); i < 8; i++) {
            afterComma += "0";
        }
        afterComma += fractionalPart.replace("0+$", "");
    }
    String result = negative + amount + afterComma;
    while (result.lastIndexOf("0") == result.length() - 1 && result.contains(".")) {
        result = result.substring(0, result.length() - 1);
    }
    if (result.lastIndexOf(".") == result.length() - 1) {
        result = result.substring(0, result.length() - 1);
    }
    return result;
}

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  a2s  . c om*/
    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:com.chinamobile.bcbsp.util.Bytes.java

/**
 * Split passed range. Expensive operation relatively. Uses BigInteger math.
 * Useful splitting ranges for MapReduce jobs.
 *
 * @param a/* www .j a  v a2  s .  c o m*/
 *        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;
}