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.ery.ertc.estorm.util.Bytes.java

/**
 * Iterate over keys within the passed range.
 *///from  ww w.  j ava 2 s  .  c  o m
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive,
        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));
    BigInteger diffBI = stopBI.subtract(startBI);
    if (inclusive) {
        diffBI = diffBI.add(BigInteger.ONE);
    }
    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: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.apache.kylin.common.util.Bytes.java

/**
 * Iterate over keys within the passed range.
 *//*www  . j a va2s . com*/
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive,
        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));
    BigInteger diffBI = stopBI.subtract(startBI);
    if (inclusive) {
        diffBI = diffBI.add(BigInteger.ONE);
    }
    final BigInteger splitsBI = BigInteger.valueOf(num + 1L);
    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:Ternary.java

public BigInteger toBigInteger() {
    BigInteger toRet = BigInteger.ZERO;
    BigInteger curr;//w ww  .j  a v a 2s  .c o m
    for (int pos = 0; pos < trits.size(); pos++) {
        curr = (biThree.pow(pos)).multiply(BigInteger.valueOf(getTrit(pos).toInt()));
        toRet = toRet.add(curr);
    }

    return toRet;
}

From source file:com.lenovo.tensorhusky.common.utils.ProcfsBasedProcessTree.java

private BigInteger getTotalProcessJiffies() {
    BigInteger totalStime = BigInteger.ZERO;
    long totalUtime = 0;
    for (ProcessInfo p : processTree.values()) {
        if (p != null) {
            totalUtime += p.getUtime();/*from   w ww  .j  a v a 2s.  c o m*/
            totalStime = totalStime.add(p.getStime());
        }
    }
    return totalStime.add(BigInteger.valueOf(totalUtime));
}

From source file:energy.usef.dso.service.business.DsoPlanboardBusinessService.java

/**
 * Sums the power of the Flex Orders.// ww  w .  j a v  a  2 s  . c  o  m
 *
 * @param ptuFlexOrders {@link List} of {@link PtuFlexOrder}.
 * @return the sum of the power.
 */
private BigInteger sumPowerOfFlexOrders(List<PtuFlexOrder> ptuFlexOrders) {
    BigInteger result = BigInteger.ZERO;
    for (PtuFlexOrder ptuFlexOrder : ptuFlexOrders) {
        if (AcknowledgementStatus.ACCEPTED != ptuFlexOrder.getAcknowledgementStatus()) {
            continue;
        }
        PtuFlexOffer ptuFlexOffer = getRelatedPtuFlexOffer(ptuFlexOrder);
        result = result.add(ptuFlexOffer.getPower());
    }
    return result;
}

From source file:org.apache.hadoop.hbase.util.Bytes.java

/**
 * Iterate over keys within the passed range.
 *///from   w ww  .j  a va2 s .  co  m
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive,
        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));
    BigInteger diffBI = stopBI.subtract(startBI);
    if (inclusive) {
        diffBI = diffBI.add(BigInteger.ONE);
    }
    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:com.netflix.imfutility.cpl._2013.Cpl2013ContextBuilderStrategy.java

private void processResourceRepeat(TrackFileResourceType trackFileResource, long repeat) {
    // 1. init resource context
    ResourceUUID resourceId = ResourceUUID.create(trackFileResource.getId(), repeat);
    ResourceKey resourceKey = ResourceKey.create(currentSegmentUuid, currentSequenceUuid, currentSequenceType);
    contextProvider.getResourceContext().initResource(resourceKey, resourceId);

    // 2. Init essence parameter in Edit Units (as defined in CPL)
    // Check that we have a corresponding track file in assetmap
    // asset map already contains full absolute paths
    UUID trackId = UUID.create(trackFileResource.getTrackFileId());
    String assetPath = assetMap.getAsset(trackId);
    if (assetPath == null) {
        throw new ConversionException(
                String.format("Resource track file '%s' isn't present in assetmap.xml", trackId));
    }/*from  www .  j  a va 2s  .  c o m*/
    assetMap.markAssetReferenced(trackId);
    contextProvider.getResourceContext().addResourceParameter(resourceKey, resourceId,
            ResourceContextParameters.ESSENCE, assetPath);

    // 3. init edit rate parameter
    BigFraction editRate = ((trackFileResource.getEditRate() != null)
            && !trackFileResource.getEditRate().isEmpty())
                    ? ConversionHelper.parseEditRate(trackFileResource.getEditRate())
                    : compositionEditRate;
    contextProvider.getResourceContext().addResourceParameter(resourceKey, resourceId,
            ResourceContextParameters.EDIT_RATE, ConversionHelper.toEditRate(editRate));

    // 4. Init startTime parameter
    BigInteger startTimeEditUnit = trackFileResource.getEntryPoint() != null ? trackFileResource.getEntryPoint()
            : BigInteger.valueOf(0);
    contextProvider.getResourceContext().addResourceParameter(resourceKey, resourceId,
            ResourceContextParameters.START_TIME_EDIT_UNIT, startTimeEditUnit.toString());

    // 5. init duration parameter
    BigInteger durationEditUnit;
    if (trackFileResource.getSourceDuration() != null) {
        durationEditUnit = trackFileResource.getSourceDuration();
    } else {
        durationEditUnit = trackFileResource.getIntrinsicDuration().subtract(startTimeEditUnit);
    }
    contextProvider.getResourceContext().addResourceParameter(resourceKey, resourceId,
            ResourceContextParameters.DURATION_EDIT_UNIT, durationEditUnit.toString());

    // 6. init endTime parameter
    BigInteger endTimeEditUnit = startTimeEditUnit.add(durationEditUnit);
    contextProvider.getResourceContext().addResourceParameter(resourceKey, resourceId,
            ResourceContextParameters.END_TIME_EDIT_UNIT, endTimeEditUnit.toString());

    // 7. init total repeat count parameter
    BigInteger repeatCount = trackFileResource.getRepeatCount() != null ? trackFileResource.getRepeatCount()
            : BigInteger.ONE;
    contextProvider.getResourceContext().addResourceParameter(resourceKey, resourceId,
            ResourceContextParameters.REPEAT_COUNT, repeatCount.toString());

    // 8. init trackFile ID
    contextProvider.getResourceContext().addResourceParameter(resourceKey, resourceId,
            ResourceContextParameters.TRACK_FILE_ID, trackId.getUuid());

    // 9. init essence descriptor ID
    String essenceDescId = trackFileResource.getSourceEncoding();
    contextProvider.getResourceContext().addResourceParameter(resourceKey, resourceId,
            ResourceContextParameters.ESSENCE_DESC_ID, essenceDescId);
}

From source file:org.medici.bia.dao.titleoccslist.TitleOccsListDAOJpaImpl.java

/**
 * {@inheritDoc}//w w w  . ja  v a2 s. com
 */
@SuppressWarnings("unchecked")
@Override
public Page searchTitlesOrOccupations(SimpleSearchTitleOrOccupation simpleSearchTitleOrOccupation,
        PaginationFilter paginationFilter) throws PersistenceException {
    // We prepare object of return method.
    Page page = new Page(paginationFilter);

    // select a.TitleOccID, a.TitleOcc, count(b.personId) from tblTitleOccsList a left outer join tblPoLink b on b.TitleOccID = a.TitleOccID group by a.titleOccID
    StringBuilder stringBuilder = new StringBuilder(
            "select a.titleOccID, a.titleOcc, count(b.personId) from tblTitleOccsList a");
    stringBuilder.append(" left join tblPoLink b on b.titleOccID = a.TitleOccID ");
    if (simpleSearchTitleOrOccupation.getTextSearch() != null) {
        stringBuilder.append(" where a.titleOcc LIKE '%");
        stringBuilder.append(simpleSearchTitleOrOccupation.getTextSearch());
        stringBuilder.append("%' ");
    } else if (simpleSearchTitleOrOccupation.getRoleCatId() != null) {
        stringBuilder.append(" where a.roleCatMinorId=");
        stringBuilder.append(simpleSearchTitleOrOccupation.getRoleCatId());
    }
    stringBuilder.append(" group by a.titleOccID ");

    // We set size of result.
    if (paginationFilter.getTotal() == null) {
        //select  count(*) from ( select count(*) from tblTitleOccsList a left outer join tblPoLink b on b.TitleOccID = a.TitleOccID group by a.titleOccID ) count
        StringBuilder queryCountBuilder = new StringBuilder("");
        queryCountBuilder.append("select count(*) from tblTitleOccsList a ");
        if (simpleSearchTitleOrOccupation.getTextSearch() != null) {
            queryCountBuilder.append(" where a.titleOcc LIKE '%");
            queryCountBuilder.append(simpleSearchTitleOrOccupation.getTextSearch());
            queryCountBuilder.append("%' ");
        } else if (simpleSearchTitleOrOccupation.getRoleCatId() != null) {
            queryCountBuilder.append(" where a.roleCatMinorID=");
            queryCountBuilder.append(simpleSearchTitleOrOccupation.getRoleCatId());
        }

        // In this case we use Native Query!!!
        Query query = getEntityManager().createNativeQuery(queryCountBuilder.toString());

        // Count(*) in native query is mapped as BigInteger, so we need to convert to Long...
        BigInteger result = (BigInteger) query.getSingleResult();
        page.setTotal(NumberUtils.createLong(result.toString()));
    }

    // We invoke native query beacuse we use left outer join with on condition 
    Query query = getEntityManager().createNativeQuery(stringBuilder.toString());
    query.setFirstResult(paginationFilter.getFirstRecord());
    query.setMaxResults(paginationFilter.getLength());

    List<Object> list = (List<Object>) query.getResultList();

    List<Object> result = new ArrayList<Object>(list.size());

    for (int i = 0; i < list.size(); i++) {
        Object[] singleRow = (Object[]) list.get(i);
        List<Object> row = new ArrayList<Object>(0);

        row.add(new TitleOccsList((Integer) singleRow[0], (String) singleRow[1]));
        row.add(NumberUtils.createLong(((BigInteger) singleRow[2]).toString()));
        result.add(row);
    }

    // We set search result on return method
    page.setList(result);

    return page;
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulatorParserHandler.java

protected String processVarValue(String value) throws SAXParseException {
    double valueNext = 0;
    double totalValue = 0;
    String symbol = null;/*from www.ja v  a  2 s  .  co  m*/

    // If addition or multiplication are specified, then do the math.
    // For now, only one or the other is permitted.
    if (value.indexOf("+") > 0 && (value.indexOf("*") > 0))
        throw new SAXParseException("Either multiplicaton or addition but not both are allowed", saxLocator);
    else if (value.indexOf("bet") > 0) {
        if ((value.substring(value.indexOf("bet") + 4, value.length()).length() > 9)) {
            BigInteger min = new BigInteger(value.substring(0, value.indexOf("bet") - 1));
            BigInteger max = new BigInteger(value.substring(value.indexOf("bet") + 4, value.length()));
            BigInteger diff = max.subtract(min);
            diff = diff.add(new BigInteger("1"));
            BigInteger rnd = new BigInteger(diff.bitLength(), random);
            BigInteger finalVal = rnd.add(min);
            value = "" + finalVal;
        } else {
            int min = Integer.parseInt(value.substring(0, value.indexOf("bet") - 1));
            int max = Integer.parseInt(value.substring(value.indexOf("bet") + 4, value.length()));
            value = "" + (random.nextInt(max - min + 1) + min);
        }
    } else if ((value.indexOf("+") > 0 && (value.indexOf("*") < 0))
            || (value.indexOf("*") > 0 && (value.indexOf("+") < 0))) {
        symbol = (value.indexOf("+") > 0) ? "+" : "*";
        totalValue = symbol.equals("*") ? 1 : 0;
        while (value.indexOf(symbol) > 0) {
            valueNext = Double.parseDouble(vars.get(value.substring(0, value.indexOf(symbol) - 1)));
            if (symbol.equals("+"))
                totalValue = totalValue + valueNext;
            else
                totalValue = totalValue * valueNext;
            value = value.substring(value.indexOf(symbol) + 2, value.length());
        }
        totalValue = symbol.equals("*") ? totalValue * Double.parseDouble(value)
                : totalValue + Double.parseDouble(vars.get(value.substring(0, value.length())));
        value = "" + totalValue;
    }
    return value;
}