Example usage for java.math BigInteger add

List of usage examples for java.math BigInteger add

Introduction

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

Prototype

BigInteger add(long val) 

Source Link

Document

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

Usage

From source file:com.amazonaws.services.kinesis.clientlibrary.proxies.util.KinesisLocalFileDataCreator.java

/**
 * Creates a temp file (in default temp file location) with fake Kinesis data records.
 * Records will be put in all shards.//from w  ww  . j a v a 2  s  .  c o  m
 * @param fileNamePrefix Prefix for the name of the temp file
 * @param shardList List of shards (we use the shardId and sequenceNumberRange fields)
 * @param numRecordsPerShard Num records per shard (the shard sequenceNumberRange should be large enough
 *     for us to allow these many records with some "holes")
 * @return File with stream data filled in
 * @throws IOException Thrown if there are issues creating/updating the file
 */
public static File generateTempDataFile(List<Shard> shardList, int numRecordsPerShard, String fileNamePrefix)
        throws IOException {
    File file = File.createTempFile(fileNamePrefix, FILE_NAME_SUFFIX);
    try (BufferedWriter fileWriter = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) {
        ObjectMapper objectMapper = new ObjectMapper();
        String serializedShardList = objectMapper
                .writeValueAsString(new KinesisLocalFileProxy.SerializedShardList(shardList));
        fileWriter.write(serializedShardList);
        fileWriter.newLine();
        BigInteger sequenceNumberIncrement = new BigInteger("0");
        long timestamp = STARTING_TIMESTAMP;
        for (int i = 0; i < numRecordsPerShard; i++) {
            for (Shard shard : shardList) {
                BigInteger sequenceNumber = new BigInteger(
                        shard.getSequenceNumberRange().getStartingSequenceNumber())
                                .add(sequenceNumberIncrement);
                String endingSequenceNumber = shard.getSequenceNumberRange().getEndingSequenceNumber();
                BigInteger maxSequenceNumber = KinesisLocalFileProxy.MAX_SEQUENCE_NUMBER;
                if (endingSequenceNumber != null) {
                    maxSequenceNumber = new BigInteger(endingSequenceNumber);
                }
                if (maxSequenceNumber.compareTo(sequenceNumber) != 1) {
                    throw new IllegalArgumentException("Not enough space in shard");
                }
                String partitionKey = PARTITION_KEY_PREFIX + shard.getShardId()
                        + generateRandomString(PARTITION_KEY_LENGTH);
                String data = generateRandomString(DATA_LENGTH);

                // Allow few records to have the same timestamps (to mimic real life scenarios).
                timestamp = (i % DIVISOR == 0) ? timestamp : timestamp + 1;
                String line = shard.getShardId() + "," + sequenceNumber + "," + partitionKey + "," + data + ","
                        + timestamp;

                fileWriter.write(line);
                fileWriter.newLine();
                sequenceNumberIncrement = sequenceNumberIncrement.add(BigInteger.ONE);
                sequenceNumberIncrement = sequenceNumberIncrement
                        .add(new BigInteger(NUM_BITS, randomGenerator));
            }
        }
    }
    return file;
}

From source file:libra.preprocess.common.kmerhistogram.KmerRangePartitioner.java

public KmerRangePartition[] getEqualAreaPartitions() {
    KmerRangePartition[] partitions = new KmerRangePartition[this.numPartitions];

    // calc 4^kmerSize
    BigInteger kmerend = BigInteger.valueOf(4).pow(this.kmerSize);
    BigDecimal bdkmerend = new BigDecimal(kmerend);
    // moves between x (0~1) y (0~1)
    // sum of area (0.5)
    double kmerArea = 0.5;
    double sliceArea = kmerArea / this.numPartitions;

    // we think triangle is horizontally flipped so calc get easier.
    double x1 = 0;

    List<BigInteger> widths = new ArrayList<BigInteger>();
    BigInteger widthSum = BigInteger.ZERO;
    for (int i = 0; i < this.numPartitions; i++) {
        // x2*x2 = 2*sliceArea + x1*x1
        double temp = (2 * sliceArea) + (x1 * x1);
        double x2 = Math.sqrt(temp);

        BigDecimal bdx1 = BigDecimal.valueOf(x1);
        BigDecimal bdx2 = BigDecimal.valueOf(x2);

        // if i increases, bdw will be decreased
        BigDecimal bdw = bdx2.subtract(bdx1);

        BigInteger bw = bdw.multiply(bdkmerend).toBigInteger();
        if (bw.compareTo(BigInteger.ZERO) <= 0) {
            bw = BigInteger.ONE;/*from  www  . ja v  a  2s .  c o m*/
        }

        if (widthSum.add(bw).compareTo(kmerend) > 0) {
            bw = kmerend.subtract(widthSum);
        }

        if (i == this.numPartitions - 1) {
            // last case
            if (widthSum.add(bw).compareTo(kmerend) < 0) {
                bw = kmerend.subtract(widthSum);
            }
        }

        // save it
        widths.add(bw);
        widthSum = widthSum.add(bw);

        x1 = x2;
    }

    BigInteger cur_begin = BigInteger.ZERO;
    for (int i = 0; i < this.numPartitions; i++) {
        BigInteger slice_width = widths.get(this.numPartitions - 1 - i);

        BigInteger slice_begin = cur_begin;

        if (slice_begin.add(slice_width).compareTo(kmerend) > 0) {
            slice_width = kmerend.subtract(slice_begin);
        }

        BigInteger slice_end = cur_begin.add(slice_width).subtract(BigInteger.ONE);

        KmerRangePartition slice = new KmerRangePartition(this.kmerSize, this.numPartitions, i, slice_width,
                slice_begin, slice_end);
        partitions[i] = slice;

        cur_begin = cur_begin.add(slice_width);
    }

    return partitions;
}

From source file:org.apache.hama.util.Bytes.java

/**
 * Split passed range. Expensive operation relatively. Uses BigInteger math.
 * /*from  ww  w .  jav  a2s. co  m*/
 * @param a 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:com.ephesoft.dcma.tablefinder.share.TableRowFinderUtility.java

/**
 * Algorithm for comparison: if old span's y coordinate's mid lies within range of new span's y coordinates or not.
 * //from  ww w  . j  a va  2s. c o  m
 * @param spanList {@link List}<{@link Span}>
 * @param span {@link Span}
 * @return boolean
 */
private static boolean isSameLineSpan(final List<Span> spanList, final Span span) {
    final Span lastSpan = spanList.get(spanList.size() - 1);
    final BigInteger s1Y0 = span.getCoordinates().getY0();
    final BigInteger s1Y1 = span.getCoordinates().getY1();
    final BigInteger s2Y0 = lastSpan.getCoordinates().getY0();
    final BigInteger s2Y1 = lastSpan.getCoordinates().getY1();
    final BigInteger s2Y = s2Y1.add(s2Y0);
    final int oldSpanMid = s2Y.intValue() / 2;
    boolean isSameLineSpan = oldSpanMid >= s1Y0.intValue() && oldSpanMid <= s1Y1.intValue();
    return isSameLineSpan;
}

From source file:org.osgp.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

private BigInteger byteArrayToBigInteger(final byte[] bitStringValue) {
    if (bitStringValue == null || bitStringValue.length == 0) {
        return null;
    }//from   ww w  .  j  a  va2  s.c o  m
    BigInteger value = BigInteger.valueOf(0);
    for (final byte element : bitStringValue) {
        value = value.shiftLeft(8);
        value = value.add(BigInteger.valueOf(element & 0xFF));
    }
    return value;
}

From source file:libra.preprocess.common.kmerhistogram.KmerRangePartitioner.java

public KmerRangePartition[] getHistogramPartitions(KmerHistogramRecord[] records, long samples) {
    KmerRangePartition[] partitions = new KmerRangePartition[this.numPartitions];

    // calc 4^kmerSize
    String As = "";
    String Ts = "";
    for (int i = 0; i < this.kmerSize; i++) {
        As += "A";
        Ts += "T";
    }/*from  w  w  w .ja  va2s.  com*/

    long partitionWidth = samples / this.numPartitions;
    long partitionWidthRemain = partitionWidth;
    int partitionIdx = 0;
    int recordIdx = 0;
    long curRecordRemain = records[0].getFrequency();
    BigInteger nextPartitionBegin = BigInteger.ZERO;
    while (partitionIdx < this.numPartitions) {
        long diff = partitionWidthRemain - curRecordRemain;
        if (diff > 0) {
            partitionWidthRemain -= curRecordRemain;
            recordIdx++;
            if (recordIdx < records.length) {
                curRecordRemain = records[recordIdx].getFrequency();
            } else {
                break;
            }
        } else if (diff == 0) {
            BigInteger partitionBegin = nextPartitionBegin;
            BigInteger partitionEnd = null;
            if (partitionIdx == this.numPartitions - 1) {
                partitionEnd = SequenceHelper.convertToBigInteger(Ts);
            } else {
                partitionEnd = SequenceHelper
                        .convertToBigInteger((records[recordIdx].getKmer() + Ts).substring(0, this.kmerSize));
            }
            BigInteger partitionSize = partitionEnd.subtract(partitionBegin);
            partitions[partitionIdx] = new KmerRangePartition(this.kmerSize, this.numPartitions, partitionIdx,
                    partitionSize, partitionBegin, partitionEnd);

            nextPartitionBegin = partitionEnd.add(BigInteger.ONE);
            partitionIdx++;
            recordIdx++;
            if (recordIdx < records.length) {
                curRecordRemain = records[recordIdx].getFrequency();
            } else {
                break;
            }
            partitionWidthRemain = partitionWidth;
        } else {
            // in between
            BigInteger partitionBegin = nextPartitionBegin;
            BigInteger partitionEnd = null;
            if (partitionIdx == this.numPartitions - 1) {
                partitionEnd = SequenceHelper.convertToBigInteger(Ts);
            } else {
                BigInteger recordBegin = SequenceHelper
                        .convertToBigInteger((records[recordIdx].getKmer() + As).substring(0, this.kmerSize));
                BigInteger recordEnd = SequenceHelper
                        .convertToBigInteger((records[recordIdx].getKmer() + Ts).substring(0, this.kmerSize));
                BigInteger recordWidth = recordEnd.subtract(recordBegin);
                BigInteger curWidth = recordWidth.multiply(BigInteger.valueOf(partitionWidthRemain))
                        .divide(BigInteger.valueOf(records[recordIdx].getFrequency()));

                BigInteger bigger = null;
                if (recordBegin.compareTo(partitionBegin) > 0) {
                    bigger = recordBegin;
                } else {
                    bigger = partitionBegin;
                }

                partitionEnd = bigger.add(curWidth);
            }
            BigInteger partitionSize = partitionEnd.subtract(partitionBegin);
            partitions[partitionIdx] = new KmerRangePartition(this.kmerSize, this.numPartitions, partitionIdx,
                    partitionSize, partitionBegin, partitionEnd);

            nextPartitionBegin = partitionEnd.add(BigInteger.ONE);
            partitionIdx++;
            curRecordRemain -= partitionWidthRemain;
            partitionWidthRemain = partitionWidth;
        }
    }

    return partitions;
}

From source file:info.savestate.saveybot.JSONFileManipulator.java

public String lowestSlot() {
    BigInteger lowest = BigInteger.ZERO;
    JSONArray json = getJSON();//from   w ww  . ja  v a  2 s  .  c om
    boolean passed = false;
    while (!passed) {
        passed = true;
        for (int i = 0; i < json.length(); i++) {
            JSONObject o = json.getJSONObject(i);
            BigInteger current = o.getBigInteger("slot");
            if (current.compareTo(lowest) == 0) {
                lowest = lowest.add(BigInteger.ONE);
                passed = false;
                break;
            }
        }
    }
    return lowest.toString();
}

From source file:net.ripe.ipresource.IpRange.java

public List<IpRange> splitToPrefixes() {
    BigInteger rangeEnd = getEnd().getValue();
    BigInteger currentRangeStart = getStart().getValue();
    int startingPrefixLength = getType().getBitSize();
    List<IpRange> prefixes = new LinkedList<IpRange>();

    while (currentRangeStart.compareTo(rangeEnd) <= 0) {
        int maximumPrefixLength = getMaximumLengthOfPrefixStartingAtIpAddressValue(currentRangeStart,
                startingPrefixLength);//from  ww w  .ja va2 s  .  c  o m
        BigInteger maximumSizeOfPrefix = rangeEnd.subtract(currentRangeStart).add(BigInteger.ONE);
        BigInteger currentSizeOfPrefix = BigInteger.valueOf(2).pow(maximumPrefixLength);

        while ((currentSizeOfPrefix.compareTo(maximumSizeOfPrefix) > 0) && (maximumPrefixLength > 0)) {
            maximumPrefixLength--;
            currentSizeOfPrefix = BigInteger.valueOf(2).pow(maximumPrefixLength);
        }

        BigInteger currentRangeEnd = currentRangeStart
                .add(BigInteger.valueOf(2).pow(maximumPrefixLength).subtract(BigInteger.ONE));
        IpRange prefix = (IpRange) IpResourceRange.assemble(currentRangeStart, currentRangeEnd, getType());

        prefixes.add(prefix);

        currentRangeStart = currentRangeEnd.add(BigInteger.ONE);
    }

    return prefixes;
}

From source file:com.google.bitcoin.core.Block.java

/**
 * Returns the work represented by this block.<p>
 *
 * Work is defined as the number of tries needed to solve a block in the
 * average case. Consider a difficulty target that covers 5% of all possible
 * hash values. Then the work of the block will be 20. As the target gets
 * lower, the amount of work goes up./* w  w w  .j  a v a  2  s. c  o m*/
 */
public BigInteger getWork() throws VerificationException {
    BigInteger target = getDifficultyTargetAsInteger();
    return LARGEST_HASH.divide(target.add(BigInteger.ONE));
}

From source file:com.amazonaws.kinesis.agg.AggRecord.java

/**
 * Calculate a new explicit hash key based on the input partition key (following
 * the algorithm from the original KPL).
 * /*www. ja va 2  s  .c  o  m*/
 * @param partitionKey
 *            The partition key to seed the new explicit hash key with
 * @return An explicit hash key based on the input partition key generated using
 *         an algorithm from the original KPL.
 */
private String createExplicitHashKey(final String partitionKey) {
    BigInteger hashKey = BigInteger.ZERO;

    this.md5.reset();
    byte[] pkDigest = this.md5.digest(partitionKey.getBytes(StandardCharsets.UTF_8));

    for (int i = 0; i < this.md5.getDigestLength(); i++) {
        BigInteger p = new BigInteger(String.valueOf((int) pkDigest[i] & 0xFF)); // convert
        // to
        // unsigned
        // integer
        BigInteger shifted = p.shiftLeft((16 - i - 1) * 8);
        hashKey = hashKey.add(shifted);
    }

    return hashKey.toString(10);
}