Example usage for java.math BigInteger compareTo

List of usage examples for java.math BigInteger compareTo

Introduction

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

Prototype

public int compareTo(BigInteger val) 

Source Link

Document

Compares this BigInteger with the specified BigInteger.

Usage

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";
    }/*www  .  ja va 2s  .  c  o m*/

    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:org.trnltk.numeral.DigitsToTextConverter.java

public String convert(String digits) {
    if (StringUtils.isBlank(digits))
        return null;

    digits = digits.replaceAll(GROUPING_SEPARATOR_REGEX, StringUtils.EMPTY);

    if (!TURKISH_NUMBER_PATTERN.matcher(digits).matches())
        throw new IllegalArgumentException("'" + digits
                + "' is not a valid Turkish number. Allowed pattern is : " + TURKISH_NUMBER_PATTERN.pattern());

    String strIntegerPart, strFractionPart;

    if (digits.contains(FRACTION_SEPARATOR)) {
        strIntegerPart = digits.substring(0, digits.indexOf(FRACTION_SEPARATOR));
        strFractionPart = digits.substring(digits.indexOf(FRACTION_SEPARATOR) + 1);
    } else {//from  w  w w  .  j  a v  a  2  s  .  c o m
        strIntegerPart = digits;
        strFractionPart = null;
    }

    boolean isPositive = true;
    if (strIntegerPart.startsWith(POSITIVE_SIGN)) {
        isPositive = true;
        strIntegerPart = strIntegerPart.substring(1);
    }
    if (strIntegerPart.startsWith(NEGATIVE_SIGN)) {
        isPositive = false;
        strIntegerPart = strIntegerPart.substring(1);
    }

    BigInteger integerPart = new BigInteger(strIntegerPart);
    BigInteger fractionPart = StringUtils.isNotBlank(strFractionPart) ? new BigInteger(strFractionPart)
            : BigInteger.ZERO;

    if (!isPositive)
        integerPart = integerPart.negate();

    String wordIntegerPart = this.convertNaturalNumberToWords(integerPart.abs());
    String wordFractionPart = this.convertNaturalNumberToWords(fractionPart);

    wordIntegerPart = this.addTextForLeadingZeros(strIntegerPart, wordIntegerPart);
    wordFractionPart = StringUtils.isNotBlank(strFractionPart)
            ? this.addTextForLeadingZeros(strFractionPart, wordFractionPart)
            : wordFractionPart;

    if (integerPart.compareTo(ZERO) < 0)
        wordIntegerPart = MINUS_NAME + " " + wordIntegerPart;

    if (digits.contains(FRACTION_SEPARATOR))
        return wordIntegerPart + " " + COMMA_NAME + " " + wordFractionPart;
    else
        return wordIntegerPart;
}

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

/** Returns true if the hash of the block is OK (lower than difficulty target). */
private boolean checkProofOfWork(boolean throwException) throws VerificationException {
    // This part is key - it is what proves the block was as difficult to make as it claims
    // to be. Note however that in the context of this function, the block can claim to be
    // as difficult as it wants to be .... if somebody was able to take control of our network
    // connection and fork us onto a different chain, they could send us valid blocks with
    // ridiculously easy difficulty and this function would accept them.
    ///* ww  w.  j  av  a  2s  . c  om*/
    // To prevent this attack from being possible, elsewhere we check that the difficultyTarget
    // field is of the right value. This requires us to have the preceeding blocks.
    BigInteger target = getDifficultyTargetAsInteger();

    BigInteger h = getHash().toBigInteger();
    if (h.compareTo(target) > 0) {
        // Proof of work check failed!
        if (throwException)
            throw new VerificationException(
                    "Hash is higher than target: " + getHashAsString() + " vs " + target.toString(16));
        else
            return false;
    }
    return true;
}

From source file:org.lwes.db.EventTemplateDB.java

/**
 * This method checks the type and range of a default value (from the ESF).
 * It returns the desired form, if allowed.
 *
 * @param type     which controls the desired object type of the value
 * @param esfValue which should be converted to fit 'type'
 * @return a value suitable for storing in a BaseType of this 'type'
 * @throws EventSystemException if the value is not acceptable for the type.
 *//* w w  w  . ja  va 2  s  .  c o  m*/
@SuppressWarnings("cast")
private Object canonicalizeDefaultValue(String eventName, String attributeName, FieldType type, Object esfValue)
        throws EventSystemException {
    try {
        switch (type) {
        case BOOLEAN:
            return (Boolean) esfValue;
        case BYTE:
            checkRange(eventName, attributeName, esfValue, Byte.MIN_VALUE, Byte.MAX_VALUE);
            return ((Number) esfValue).byteValue();
        case INT16:
            checkRange(eventName, attributeName, esfValue, Short.MIN_VALUE, Short.MAX_VALUE);
            return ((Number) esfValue).shortValue();
        case INT32:
            checkRange(eventName, attributeName, esfValue, Integer.MIN_VALUE, Integer.MAX_VALUE);
            return ((Number) esfValue).intValue();
        case UINT16:
            checkRange(eventName, attributeName, esfValue, 0, 0x10000);
            return ((Number) esfValue).intValue() & 0xffff;
        case UINT32:
            checkRange(eventName, attributeName, esfValue, 0, 0x100000000L);
            return ((Number) esfValue).longValue() & 0xffffffff;
        case FLOAT:
            return ((Number) esfValue).floatValue();
        case DOUBLE:
            return ((Number) esfValue).doubleValue();
        case STRING:
            return ((String) esfValue);
        case INT64: {
            if (esfValue instanceof Long) {
                return esfValue;
            }
            final BigInteger bi = (BigInteger) esfValue;
            if (bi.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0
                    || bi.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
                throw new EventSystemException(
                        String.format("Field %s.%s value %s outside allowed range [%d,%d]", eventName,
                                attributeName, esfValue, Long.MIN_VALUE, Long.MAX_VALUE));
            }
            return bi.longValue();
        }
        case UINT64: {
            if (esfValue instanceof BigInteger) {
                return esfValue;
            }
            return BigInteger.valueOf(((Number) esfValue).longValue());
        }
        case IPADDR:
            return ((IPAddress) esfValue);
        case BOOLEAN_ARRAY:
        case BYTE_ARRAY:
        case DOUBLE_ARRAY:
        case FLOAT_ARRAY:
        case INT16_ARRAY:
        case INT32_ARRAY:
        case INT64_ARRAY:
        case IP_ADDR_ARRAY:
        case STRING_ARRAY:
        case UINT16_ARRAY:
        case UINT32_ARRAY:
        case UINT64_ARRAY:
        case NBOOLEAN_ARRAY:
        case NBYTE_ARRAY:
        case NDOUBLE_ARRAY:
        case NFLOAT_ARRAY:
        case NINT16_ARRAY:
        case NINT32_ARRAY:
        case NINT64_ARRAY:
        case NSTRING_ARRAY:
        case NUINT16_ARRAY:
        case NUINT32_ARRAY:
        case NUINT64_ARRAY:
            throw new EventSystemException("Unsupported default value type " + type);
        }
        throw new EventSystemException("Unrecognized type " + type + " for value " + esfValue);
    } catch (ClassCastException e) {
        throw new EventSystemException("Type " + type + " had an inappropriate default value " + esfValue);
    }
}

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

/**
 * Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the
 * target is represented using a compact form. If this form decodes to a value that is out of bounds, an exception
 * is thrown./*from  w ww  .  j  a  va2  s  . c  o m*/
 */
public BigInteger getDifficultyTargetAsInteger() throws VerificationException {
    maybeParseHeader();
    BigInteger target = Utils.decodeCompactBits(difficultyTarget);
    if (target.compareTo(BigInteger.valueOf(0)) <= 0 || target.compareTo(params.proofOfWorkLimit) > 0)
        throw new VerificationException("Difficulty target is bad: " + target.toString());
    return target;
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

private BigInteger[] preventMalleability(BigInteger[] sigs, BigInteger curveN) {
    BigInteger cmpVal = curveN.divide(BigInteger.valueOf(2L));

    BigInteger sval = sigs[1];

    if (sval.compareTo(cmpVal) == 1) {

        sigs[1] = curveN.subtract(sval);
    }/*from  w w w. ja  v  a  2  s  .co  m*/

    return sigs;
}

From source file:com.fratello.longevity.smooth.object.SpecialFile.java

private boolean testFilterProperty_Size(SpecialFile other) {
    String byteType = this.filter.getMetricSize();
    BigInteger sourceSize = new BigInteger(String.valueOf(this.SIZE));
    BigInteger targetSize = new BigInteger(String.valueOf(other.SIZE));
    String num = "";
    switch (byteType) {
    default://from   ww w .  ja v  a 2 s  .  c o m
    case "BYTE":
        num = "1";
        break;
    case "KILOBYTE":
        num = "1024";
        break;
    case "MEGABYTE":
        num = "1048576";
        break;
    case "GIGABYTE":
        num = "1073741824";
        break;
    }
    sourceSize.multiply(new BigInteger(String.valueOf(num)));
    targetSize.multiply(new BigInteger(String.valueOf(num)));
    boolean sourceSizeIsBiggest = sourceSize.compareTo(targetSize) > 0;
    double requiredPercent = this.filter.getSizePercentMatchDouble();
    if (sourceSizeIsBiggest) {
        double matchPercent = targetSize.divide(sourceSize).doubleValue();
        if (!(matchPercent >= requiredPercent))
            return false;
    } else {
        double matchPercent = sourceSize.divide(targetSize).doubleValue();
        if (!(matchPercent >= requiredPercent))
            return false;
    }
    return true;
}

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

private void stepThree(final int i) throws Exception {
    BigInteger n = this.pubKey.getModulus();
    BigInteger r;
    BigInteger upperBound;//from  ww w . jav  a 2s.  c  om
    BigInteger lowerBound;
    BigInteger max;
    BigInteger min;
    BigInteger[] tmp;
    ArrayList<Interval> ms = new ArrayList<>(15);

    for (Interval interval : this.m) {
        upperBound = step3ComputeUpperBound(this.si, n, interval.upper);
        lowerBound = step3ComputeLowerBound(this.si, n, interval.lower);

        r = lowerBound;
        // lowerBound <= r <= upperBound
        while (r.compareTo(upperBound) < 1) {
            // ceil((2*B+r*n)/si)
            max = (BigInteger.valueOf(2).multiply(this.bigB)).add(r.multiply(n));
            tmp = max.divideAndRemainder(this.si);
            if (BigInteger.ZERO.compareTo(tmp[1]) != 0) {
                max = tmp[0].add(BigInteger.ONE);
            } else {
                max = tmp[0];
            }

            // floor((3*B-1+r*n)/si
            min = BigInteger.valueOf(3).multiply(this.bigB);
            min = min.subtract(BigInteger.ONE);
            min = min.add(r.multiply(n));
            min = min.divide(this.si);

            // build new interval
            if (interval.lower.compareTo(max) > 0) {
                max = interval.lower;
            }
            if (interval.upper.compareTo(min) < 0) {
                min = interval.upper;
            }
            if (max.compareTo(min) <= 0) {
                ms.add(new Interval(max, min));
            }
            // one further....
            r = r.add(BigInteger.ONE);
        }
    }

    loggerInstance.log(getClass(), " # of intervals for M" + i + ": " + ms.size(), Logger.LogLevel.INFO);

    if (ms.size() == 0) {
        throw new Exception("Zero intervals left, validity oracle seems to be wrong!");
    }

    this.m = ms.toArray(new Interval[ms.size()]);
}

From source file:com.ephesoft.dcma.tablefinder.share.TableRowFinderUtility.java

/**
 * Gets sorted list of spans of the page.
 * //from  w  w w .j a  va2s . com
 * @param spans {@link Spans}
 * @return {@link List}<{@link Span}>
 */
private static List<Span> getSortedSpanList(final Spans spans) {
    final List<Span> spanList = spans.getSpan();
    final Set<Span> set = new TreeSet<Span>(new Comparator<Span>() {

        public int compare(final Span firstSpan, final Span secSpan) {
            BigInteger s1Y0 = firstSpan.getCoordinates().getY0();
            BigInteger s1Y1 = firstSpan.getCoordinates().getY1();
            final BigInteger s2Y0 = secSpan.getCoordinates().getY0();
            final BigInteger s2Y1 = secSpan.getCoordinates().getY1();
            int halfOfSecSpan = (s2Y1.intValue() - s2Y0.intValue()) / 2;
            int y1 = s2Y1.intValue() + halfOfSecSpan;
            int y0 = s2Y0.intValue() - halfOfSecSpan;

            // following if else code is to handle abnormal(out of synch) value y0 or y1 coordinate of new span.
            if (isApproxEqual(s1Y0.intValue(), s2Y0.intValue()) && s1Y1.intValue() > y1) {
                s1Y1 = BigInteger.valueOf(y1);
                firstSpan.getCoordinates().setY1(s1Y1);
            } else if (isApproxEqual(s1Y1.intValue(), s2Y1.intValue()) && s1Y0.intValue() < y0) {
                s1Y0 = BigInteger.valueOf(y0);
                firstSpan.getCoordinates().setY0(s1Y0);
            }
            final BigInteger s1Y = s1Y1.add(s1Y0);
            final BigInteger s2Y = s2Y1.add(s2Y0);

            // calculating middle of old span.
            final int oldSpanMid = s2Y.intValue() / 2;
            int returnValue = 0;

            // if old span's y coordinate's middle lies within range of new span's y coordinates or not. if true, the two spans
            // belong to same line compare them further on their x coordinates, else they belong to two different lines.
            if (oldSpanMid >= s1Y0.intValue() && oldSpanMid <= s1Y1.intValue()) {
                final BigInteger s1X1 = firstSpan.getCoordinates().getX1();
                final BigInteger s2X1 = secSpan.getCoordinates().getX1();
                returnValue = s1X1.compareTo(s2X1);
            } else {
                returnValue = s1Y.compareTo(s2Y);
            }
            return returnValue;
        }

    });

    set.addAll(spanList);

    final List<Span> linkedList = new LinkedList<Span>();
    linkedList.addAll(set);

    // TODO add the clear method to remove all elements of set since it not required after adding it to linked list.
    // set.clear();

    return linkedList;
}

From source file:de.tudarmstadt.ukp.csniper.webapp.project.ProjectRepository.java

/**
 * Gets the maximum column length.<br>
 * Why is this method located here? For convenience reasons - we already have access to
 * projectRepository on the relevant pages (EvaluationPage, AnnotationTypePage).
 * /* ww  w.  j ava2  s.c om*/
 * @param aColumn
 *            the column for which the maximum length shall be returned
 * @return the maximum length of the specified column in the specified table
 */
@Transactional
public int getDbColumnLength(String aEntityName, String aColumn) {
    BigInteger length = new BigInteger("255");

    final List<String> query = new ArrayList<String>();
    query.add("SELECT CHARACTER_MAXIMUM_LENGTH");
    query.add("FROM INFORMATION_SCHEMA.COLUMNS");

    Session session = entityManager.unwrap(Session.class);
    session.doWork(new Work() {
        @Override
        public void execute(Connection aConnection) throws SQLException {
            query.add("WHERE table_schema = '" + aConnection.getCatalog() + "'");
        }
    });

    query.add("AND table_name = '" + aEntityName + "'");
    query.add("AND column_name = '" + aColumn + "'");

    try {
        length = (BigInteger) entityManager.createNativeQuery(StringUtils.join(query, " ")).getSingleResult();
    } catch (NoResultException e) {
        // log.debug("No results for query: " + StringUtils.join(query, " "));
    }

    if (length.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
        return Integer.MAX_VALUE;
    } else {
        return length.intValue();
    }
}