Java Code Examples for java.math.BigInteger.compareTo()

The following are Jave code examples for showing how to use compareTo() of the java.math.BigInteger class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: TestFDBigInteger.java   View Source Code Vote up 6 votes
private static void testCmp(FDBigInteger t, FDBigInteger o) throws Exception {
    BigInteger bt = t.toBigInteger();
    BigInteger bo = o.toBigInteger();
    int cmp = t.cmp(o);
    int bcmp = bt.compareTo(bo);
    if (bcmp != cmp) {
        throw new Exception("cmp returns " + cmp + " expected " + bcmp);
    }
    check(bt, t, "cmp corrupts this");
    check(bo, o, "cmp corrupts other");
    if (o.cmp(t) != -cmp) {
        throw new Exception("asymmetrical cmp");
    }
    check(bt, t, "cmp corrupts this");
    check(bo, o, "cmp corrupts other");
}
 
Example 2
Project: AppCoins-ethereumj   File: ParentGasLimitRule.java   View Source Code Vote up 6 votes
@Override
public boolean validate(BlockHeader header, BlockHeader parent) {

    errors.clear();
    BigInteger headerGasLimit = new BigInteger(1, header.getGasLimit());
    BigInteger parentGasLimit = new BigInteger(1, parent.getGasLimit());

    if (headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(GAS_LIMIT_BOUND_DIVISOR - 1)).divide(BigInteger.valueOf(GAS_LIMIT_BOUND_DIVISOR))) < 0 ||
        headerGasLimit.compareTo(parentGasLimit.multiply(BigInteger.valueOf(GAS_LIMIT_BOUND_DIVISOR + 1)).divide(BigInteger.valueOf(GAS_LIMIT_BOUND_DIVISOR))) > 0) {

        errors.add(String.format(
                "#%d: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR",
                header.getNumber()
        ));
        return false;
    }

    return true;
}
 
Example 3
Project: openNaEF   File: SnmpUtil.java   View Source Code Vote up 6 votes
public static int[] decodeBitListFromBigInteger(BigInteger bits) {
    List<Integer> resultList = new ArrayList<Integer>();
    BigInteger mask = BigInteger.ONE;
    int valueCandidate = 1;
    while (mask.compareTo(bits) <= 0) {
        if ((mask.and(bits)).equals(mask)) {
            resultList.add(Integer.valueOf(valueCandidate));
        }
        valueCandidate++;
        mask = mask.shiftLeft(1);
    }

    int[] result = new int[resultList.size()];
    for (int i = 0; i < result.length; i++) {
        result[i] = resultList.get(i).intValue();
    }
    return result;
}
 
Example 4
Project: ATEBot   File: MathHelp.java   View Source Code Vote up 6 votes
public static Map<BigInteger, BigInteger> decomposition(BigInteger n) throws Exception{
	if(n.compareTo(BigInteger.ONE)!=1) throw new Exception("Not a positive integer.");
	BigInteger max = bigIntSqRootCeil(n);
	Map<BigInteger, BigInteger> map = new HashMap<BigInteger,BigInteger>();
	for (BigInteger i = BigInteger.valueOf(2L); i.compareTo(max)<1;i=i.add(BigInteger.ONE)) {
		boolean ipremier = true;
		if(!i.equals(BigInteger.valueOf(2L)))
			for (BigInteger j = BigInteger.valueOf(2L); j.compareTo(bigIntSqRootCeil(i))<1 && ipremier; j=j.add(BigInteger.ONE)){
				if(i.mod(j).intValue()==0)ipremier=false;
			}
		if(!ipremier) continue;
		if(n.mod(i).intValue()==0){
			map.put(i, map.getOrDefault(i, BigInteger.ZERO).add(BigInteger.ONE));
			n=n.divide(i);
			max = bigIntSqRootCeil(n);
			i=BigInteger.ONE;
		}
	}
	map.put(n, map.getOrDefault(n, BigInteger.ZERO).add(BigInteger.ONE));
	return map;
}
 
Example 5
Project: Cybernet-VPN   File: NetworkSpace.java   View Source Code Vote up 6 votes
String getIPv6Address() {
    if (BuildConfig.DEBUG) Assert.assertTrue(!isV4);
    BigInteger r = netAddress;
    String ipv6str = null;
    boolean lastPart = true;
    while (r.compareTo(BigInteger.ZERO) == 1) {
        long part = r.mod(BigInteger.valueOf(0x10000)).longValue();
        if (ipv6str != null || part != 0) {
            if (ipv6str == null && !lastPart) ipv6str = ":";
            if (lastPart) ipv6str = String.format(Locale.US, "%x", part, ipv6str);
            else ipv6str = String.format(Locale.US, "%x:%s", part, ipv6str);
        }
        r = r.shiftRight(16);
        lastPart = false;
    }
    if (ipv6str == null) return "::";
    return ipv6str;
}
 
Example 6
Project: dble   File: FieldNum.java   View Source Code Vote up 6 votes
@Override
public int compareTo(Field other) {
    if (other == null || !(other instanceof FieldNum)) {
        return 1;
    }
    FieldNum bOther = (FieldNum) other;
    BigInteger intValue1 = this.valInt();
    BigInteger intValue2 = bOther.valInt();
    if (intValue1 == null && intValue2 == null)
        return 0;
    else if (intValue2 == null)
        return 1;
    else if (intValue1 == null)
        return -1;
    else
        return intValue1.compareTo(intValue2);
}
 
Example 7
Project: openjdk-jdk10   File: PrimeTest.java   View Source Code Vote up 6 votes
/**
 * Verifies whether the fraction of probable primes detected is at least 1 -
 * 1/2^certainty.
 *
 * @return true if and only if the test succeeds
 */
private static boolean checkPrime(Set<BigInteger> primes,
        int certainty,
        boolean parallel) {
    long probablePrimes = (parallel ? primes.parallelStream() : primes.stream())
            .filter(bi -> bi.isProbablePrime(certainty))
            .count();

    // N = certainty / 2
    // Success if p/t >= 1 - 1/4^N
    // or (p/t)*4^N >= 4^N - 1
    // or p*4^N >= t*(4^N - 1)
    BigInteger p = BigInteger.valueOf(probablePrimes);
    BigInteger t = BigInteger.valueOf(primes.size());
    BigInteger fourToTheC = BigInteger.valueOf(4).pow(certainty / 2);
    BigInteger fourToTheCMinusOne = fourToTheC.subtract(BigInteger.ONE);
    BigInteger left = p.multiply(fourToTheC);
    BigInteger right = t.multiply(fourToTheCMinusOne);

    if (left.compareTo(right) < 0) {
        System.err.println("Probable prime certainty test failed");
    }

    return left.compareTo(right) >= 0;
}
 
Example 8
Project: lokalized-java   File: NumberUtils.java   View Source Code Vote up 5 votes
/**
 * Is the first number less than the second number?
 *
 * @param number1 the first number to compare, not null
 * @param number2 the second number to compare, not null
 * @return true if the first number is less than the second number, not null
 */
@Nonnull
static Boolean lessThan(@Nonnull BigInteger number1, @Nonnull BigInteger number2) {
  requireNonNull(number1);
  requireNonNull(number2);

  return number1.compareTo(number2) < 0;
}
 
Example 9
Project: jdk8u-jdk   File: DerInputBuffer.java   View Source Code Vote up 5 votes
/**
 * Returns the integer which takes up the specified number
 * of bytes in this buffer.
 * @throws IOException if the result is not within the valid
 * range for integer, i.e. between Integer.MIN_VALUE and
 * Integer.MAX_VALUE.
 * @param len the number of bytes to use.
 * @return the integer.
 */
public int getInteger(int len) throws IOException {

    BigInteger result = getBigInteger(len, false);
    if (result.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0) {
        throw new IOException("Integer below minimum valid value");
    }
    if (result.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
        throw new IOException("Integer exceeds maximum valid value");
    }
    return result.intValue();
}
 
Example 10
Project: ipack   File: GMSSPrivateKey.java   View Source Code Vote up 5 votes
private static int checkBigIntegerInIntRange(ASN1Encodable a)
{
    BigInteger b = ((ASN1Integer)a).getValue();
    if ((b.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) ||
        (b.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0))
    {
        throw new IllegalArgumentException("BigInteger not in Range: " + b.toString());
    }
    return b.intValue();
}
 
Example 11
Project: chvote-protocol-poc   File: RandomGenerator.java   View Source Code Vote up 5 votes
/**
 * @param upperbound exclusive upperbound
 * @return a random BigInteger in range [0, upperbound)
 */
public BigInteger randomBigInteger(BigInteger upperbound) {
    for (int i = 0; i < MAX_ITERATIONS; i++) {
        BigInteger x = new BigInteger(upperbound.bitLength(), secureRandom);
        if (x.compareTo(upperbound) < 0) {
            return x;
        }
    }

    // If we fail to get a value within range for MAX_ITERATIONS, get a value with lower bitCount
    return new BigInteger(upperbound.bitLength() - 1, secureRandom);
}
 
Example 12
Project: Positive-Integers-Porperties   File: MathFunctions.java   View Source Code Vote up 5 votes
/**
 * Evaluates the number of digits of a {@link BigInteger}.
 *
 * @param  n The BigInteger to be tested.
 * @throws NullPointerException if {@code n} is null.
 * @throws IllegalArgumentException if {@code n} is less than or equal to zero.
 * @return an {@link Integer} representing the number of digits.
 */
public static Integer digits(final BigInteger n) {

    if (n == null)
        throw new NullPointerException("n value can't be null");

    if (n.compareTo(ZERO) <= 0)
        throw new IllegalArgumentException("n value must be greater than zero");

    return n.toString().length();
}
 
Example 13
Project: Hydrograph   File: ModifyListenerForDBComp.java   View Source Code Vote up 5 votes
/**
 * The Function will compare bigInteger values
 * @param value1
 * @param value2
 * @return
 */
private int compareBigIntegerValue(String value1, String value2){
	BigInteger int1= BigInteger.valueOf(Long.parseLong(value1));
	BigInteger int2 = BigInteger.valueOf(Long.parseLong(value2));
	
	return int1.compareTo(int2);
}
 
Example 14
Project: fdt   File: DhExchange.java   View Source Code Vote up 5 votes
/**
 * @param f
 */
public void setF(BigInteger f) {
    if (e == null)
        throw new IllegalStateException("DhDsaExchange not initialized!");

    BigInteger zero = BigInteger.valueOf(0);

    if (zero.compareTo(f) >= 0 || p.compareTo(f) <= 0)
        throw new IllegalArgumentException("Invalid f specified!");

    this.f = f;
    this.k = f.modPow(x, p);
}
 
Example 15
Project: jdk8u-jdk   File: TestFDBigInteger.java   View Source Code Vote up 5 votes
private static void testAddAndCmp(FDBigInteger t, FDBigInteger x, FDBigInteger y) throws Exception {
    BigInteger bt = t.toBigInteger();
    BigInteger bx = x.toBigInteger();
    BigInteger by = y.toBigInteger();
    int cmp = t.addAndCmp(x, y);
    int bcmp = bt.compareTo(bx.add(by));
    if (bcmp != cmp) {
        throw new Exception("addAndCmp returns " + cmp + " expected " + bcmp);
    }
    check(bt, t, "addAndCmp corrupts this");
    check(bx, x, "addAndCmp corrupts x");
    check(by, y, "addAndCmp corrupts y");
}
 
Example 16
Project: ipack   File: X509V3CertificateGenerator.java   View Source Code Vote up 5 votes
/**
 * set the serial number for the certificate.
 */
public void setSerialNumber(
    BigInteger      serialNumber)
{
    if (serialNumber.compareTo(BigInteger.ZERO) <= 0)
    {
        throw new IllegalArgumentException("serial number must be a positive integer");
    }
    
    tbsGen.setSerialNumber(new ASN1Integer(serialNumber));
}
 
Example 17
Project: ipack   File: ECNRSigner.java   View Source Code Vote up 4 votes
/**
 * return true if the value r and s represent a signature for the 
 * message passed in. Generally, the order of the curve should be at 
 * least as long as the hash of the message of interest, and with 
 * ECNR, it *must* be at least as long.  But just in case the signer
 * applied mod(n) to the longer digest, this implementation will
 * apply mod(n) during verification.
 *
 * @param digest  the digest to be verified.
 * @param r       the r value of the signature.
 * @param s       the s value of the signature.
 * @exception DataLengthException if the digest is longer than the key allows
 */
public boolean verifySignature(
    byte[]      digest,
    BigInteger  r,
    BigInteger  s)
{
    if (this.forSigning) 
    {
        throw new IllegalStateException("not initialised for verifying");
    }

    ECPublicKeyParameters pubKey = (ECPublicKeyParameters)key;
    BigInteger n = pubKey.getParameters().getN();
    int nBitLength = n.bitLength();
    
    BigInteger e = new BigInteger(1, digest);
    int eBitLength = e.bitLength();
    
    if (eBitLength > nBitLength) 
    {
        throw new DataLengthException("input too large for ECNR key.");
    }
    
    // r in the range [1,n-1]
    if (r.compareTo(ECConstants.ONE) < 0 || r.compareTo(n) >= 0) 
    {
        return false;
    }

    // s in the range [0,n-1]           NB: ECNR spec says 0
    if (s.compareTo(ECConstants.ZERO) < 0 || s.compareTo(n) >= 0) 
    {
        return false;
    }

    // compute P = sG + rW

    ECPoint G = pubKey.getParameters().getG();
    ECPoint W = pubKey.getQ();
    // calculate P using Bouncy math
    ECPoint P = ECAlgorithms.sumOfTwoMultiplies(G, s, W, r);

    // components must be bogus.
    if (P.isInfinity())
    {
        return false;
    }

    BigInteger x = P.getX().toBigInteger();
    BigInteger t = r.subtract(x).mod(n);

    return t.equals(e);
}
 
Example 18
Project: datax   File: RangeSplitUtil.java   View Source Code Vote up 4 votes
public static BigInteger[] doBigIntegerSplit(BigInteger left, BigInteger right, int expectSliceNumber) {
    if (expectSliceNumber < 1) {
        throw new IllegalArgumentException(String.format(
                "切分份数不能小于1. 此处:expectSliceNumber=[%s].", expectSliceNumber));
    }

    if (null == left || null == right) {
        throw new IllegalArgumentException(String.format(
                "对 BigInteger 进行切分时,其左右区间不能为 null. 此处:left=[%s],right=[%s].", left, right));
    }

    if (left.compareTo(right) == 0) {
        return new BigInteger[]{left, right};
    } else {
        // 调整大小顺序,确保 left < right
        if (left.compareTo(right) > 0) {
            BigInteger temp = left;
            left = right;
            right = temp;
        }

        //left < right
        BigInteger endAndStartGap = right.subtract(left);

        BigInteger step = endAndStartGap.divide(BigInteger.valueOf(expectSliceNumber));
        BigInteger remainder = endAndStartGap.remainder(BigInteger.valueOf(expectSliceNumber));

        //remainder 不可能超过expectSliceNumber,所以不需要检查remainder的 Integer 的范围

        // 这里不能 step.intValue()==0,因为可能溢出
        if (step.compareTo(BigInteger.ZERO) == 0) {
            expectSliceNumber = remainder.intValue();
        }

        BigInteger[] result = new BigInteger[expectSliceNumber + 1];
        result[0] = left;
        result[expectSliceNumber] = right;

        BigInteger lowerBound;
        BigInteger upperBound = left;
        for (int i = 1; i < expectSliceNumber; i++) {
            lowerBound = upperBound;
            upperBound = lowerBound.add(step);
            upperBound = upperBound.add((remainder.compareTo(BigInteger.valueOf(i)) >= 0)
                    ? BigInteger.ONE : BigInteger.ZERO);
            result[i] = upperBound;
        }

        return result;
    }
}
 
Example 19
Project: Positive-Integers-Porperties   File: MathFunctions.java   View Source Code Vote up 4 votes
/**
 * Tests if a {@link BigInteger} is a weird number.
 *
 * @param  n The BigInteger to be tested.
 * @param  abort An {@link AtomicBoolean} used to abort the execution
 *               for whatever reason; Can be null.
 * @throws NullPointerException if {@code n} is null.
 * @throws IllegalArgumentException if {@code n} is less than or equal to zero.
 * @return {@code true} if {@code n} is a weird number, {@code false} if not,
 *         {@code null} if aborted.
 * */
public static Boolean isWeird(final BigInteger n, final AtomicBoolean abort) {

    if (n == null)
        throw new NullPointerException("n value can't be null");

    if (n.compareTo(ZERO) <= 0)
        throw new IllegalArgumentException("n value must be greater than zero");

    final Boolean result = isSemiPerfect(n, abort);

    if (result == null)
        return null;

    final Boolean abundant = isAbundant(n, abort);

    if (abundant == null)
        return null;

    return abundant && !result;
}
 
Example 20
Project: java-ilp-connector   File: AbstractLedgerPluginEventHandler.java   View Source Code Vote up 3 votes
/**
 * Determines if the incoming transfer amount is insufficient.
 *
 * When attempting to determine the next-hop transfer amount to send as part of an Interledger payment, this connector
 * needs to ensure that it sends enough funds to get the receiver to fulfill the payment, but not so many funds that
 * this connector would lose money.
 *
 * To avoid losing money, this connector must not send more money to the next-hop than it received on the incoming
 * hop. This is accomplished by adding an FX-margin to the next-hop amount in order to ensure the amount sent out is
 * less-than the amount received in the incoming transfer.
 *
 * However, to ensure that the receiver fulfills the payment, the amount of the next-hop destination transfer must be
 * greater-than or equal to the amount (adjusted for slippage, if any) in the ILP packet (this is the amount that the
 * receiver is expecting to receive).
 *
 * Both of these concerns can be addressed as long as the amount in the packet is greater-than or equal-to the
 * calculated next-hop amount (padding with FX spread).
 *
 * For example, consider the following scenarios (each with a 1:1 FX rate and no slippage, for simplicity).
 *
 * 1.) An ILP Payment of $1 is sent with an incoming transfer of $1 into an account owned by this connector. The
 * FxEngine calculates that the outgoing payment should be $0.98 (a 2% FxSpread based upon the incoming transfer
 * amount. Since the ILP Packet amount ($1) is greater-than the amount about to be sent to the next-hop ($0.98), the
 * transfer will fail with an R01_INSUFFICIENT_SOURCE_AMOUNT error will be returned.
 *
 * 2.) An ILP Payment of $1 is sent with an incoming transfer of $2 into an account owned by this connector. The
 * FxEngine calculates that the outgoing payment should be $2 (a 2% FxSpread based upon the incoming transfer amount).
 * Since the ILP Packet amount ($1) is less-than the amount about to be sent to the next-hop ($2), the transfer will
 * succeed in the amount of $1 (which is the amount in the ILP packet) because this connector is greedy.
 *
 * 3.) An ILP Payment of $1 is sent with an incoming transfer of $0.95 into an account owned by this connector. The
 * FxEngine calculates that the outgoing payment should be $0.931 (a 2% FxSpread based upon the incoming transfer
 * amount). Since the ILP Packet amount ($1) is greater-than the amount about to be sent to the next-hop ($0.931), the
 * transfer will fail with an R01_INSUFFICIENT_SOURCE_AMOUNT error will be returned.
 *
 * 4.) An ILP Payment of $1 is sent with an incoming transfer of $1.02 into an account owned by this connector. The
 * FxEngine calculates that the outgoing payment should be $1 (a 2% FxSpread based upon the incoming transfer amount).
 * Since the ILP Packet amount ($1) is equal-to the amount about to be sent to the next-hop, the transfer will succeed
 * in the amount of $1 (which is the amount in the ILP packet).
 *
 * @param ilpPacketAmountWithSlippage A {@link BigInteger} representing the amount, in units of the final-destination
 *                                    ledger, of the ILP payment, minus allowed slippage (if any). In other words,
 *                                    this is the amount in the ILP packet, reduced by any slippage percentage
 *                                    configured in this connector.
 * @param calculatedNextHopAmount     A {@link BigInteger} representing the amount, in units of the next-hop ledger
 *                                    (which may or may not be the final destination ledger) that this connector
 *                                    _should_ pay to the next-hop, based solely on an FX+spread calculation using the
 *                                    amount in the incoming transfer.
 *
 * @see "https://github.com/interledger/rfcs/issues/316"
 */
@VisibleForTesting
protected boolean incomingTransferAmountIsInsufficient(
    final BigInteger ilpPacketAmountWithSlippage, final BigInteger calculatedNextHopAmount
) {
  return ilpPacketAmountWithSlippage.compareTo(calculatedNextHopAmount) > 0;
}