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

The following examples show how to use java.math.BigInteger#compareTo() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cloudstack   File: NetUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static BigInteger countIp6InRange(final String ip6Range) {
    if (ip6Range == null) {
        return null;
    }
    final String[] ips = ip6Range.split("-");
    final String startIp = ips[0];
    String endIp = ips[0];
    if (ips.length > 1) {
        endIp = ips[1];
    }
    try {
        final BigInteger startInt = convertIPv6AddressToBigInteger(IPv6Address.fromString(startIp));
        final BigInteger endInt = convertIPv6AddressToBigInteger(IPv6Address.fromString(endIp));
        if (endInt != null && startInt != null && startInt.compareTo(endInt) <= 0) {
            return endInt.subtract(startInt).add(BigInteger.ONE);
        }
    } catch (final IllegalArgumentException ex) {
        s_logger.error("Failed to convert a string to an IPv6 address", ex);
    }
    return null;
}
 
Example 2
/**
 * Formats a {@link BigFraction} object to produce a string.  The BigFraction
 * is output in proper format.
 *
 * @param fraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
@Override
public StringBuffer format(final BigFraction fraction,
                           final StringBuffer toAppendTo, final FieldPosition pos) {
    
    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    BigInteger num = fraction.getNumerator();
    BigInteger den = fraction.getDenominator();
    BigInteger whole = num.divide(den);
    num = num.remainder(den);
    
    if (!BigInteger.ZERO.equals(whole)) {
        getWholeFormat().format(whole, toAppendTo, pos);
        toAppendTo.append(' ');
        if (num.compareTo(BigInteger.ZERO) < 0) {
            num = num.negate();
        }
    }
    getNumeratorFormat().format(num, toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(den, toAppendTo, pos);
    
    return toAppendTo;
}
 
Example 3
Source Project: beanshell   File: Primitive.java    License: Apache License 2.0 6 votes vote down vote up
public static Primitive shrinkWrap(Object number) {
    if (!(number instanceof Number))
        throw new InterpreterError("Can only shrink wrap Number types");
    Number value = (Number) number;
    if ( Types.isFloatingpoint(number) ) {
        if ( !Double.isInfinite(value.doubleValue()) )
            return new Primitive(value.doubleValue());
        return new Primitive((BigDecimal) number);
    }
    BigInteger bi = number instanceof BigInteger
            ? (BigInteger) number : BigInteger.valueOf(value.longValue());
    if ( bi.compareTo(INTEGER_MIN) >= 0 && bi.compareTo(INTEGER_MAX) <= 0 )
        return new Primitive(bi.intValue());
    if ( bi.compareTo(LONG_MIN) >= 0 && bi.compareTo(LONG_MAX) <= 0 )
        return new Primitive(bi.longValue());
    return new Primitive(bi);
}
 
Example 4
Source Project: deeplearning4j   File: Rational.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Compute Pochhammer's symbol (this)_n.
 *
 * @param n The number of product terms in the evaluation.
 * @return Gamma(this+n)/Gamma(this) = this*(this+1)*...*(this+n-1).
 */
public Rational Pochhammer(final BigInteger n) {
    if (n.compareTo(BigInteger.ZERO) < 0) {
        return null;
    } else if (n.compareTo(BigInteger.ZERO) == 0) {
        return Rational.ONE;
    } else {
        /* initialize results with the current value
         */
        Rational res = new Rational(a, b);
        BigInteger i = BigInteger.ONE;
        for (; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) {
            res = res.multiply(add(i));
        }
        return res;
    }
}
 
Example 5
private static Number parseHexNumber(String hexNumberString) throws NumberFormatException {
	if (!isHexNumber(hexNumberString)) {
		throw new NumberFormatException("Not a hex number: '" + hexNumberString + "'");
	} else {
		if (hexNumberString.length() < 12) {
			return Integer.parseInt(hexNumberString.substring(2), 16);
		} else {
			BigInteger value = new BigInteger(hexNumberString.substring(2), 16);
			boolean isInteger = new BigInteger(Integer.toString(Integer.MIN_VALUE)).compareTo(value) == -1 && value.compareTo(new BigInteger(Integer.toString(Integer.MAX_VALUE))) == -1;
			if (isInteger) {
				return Integer.parseInt(hexNumberString.substring(2), 16);
			} else {
				boolean isLong = new BigInteger(Long.toString(Long.MIN_VALUE)).compareTo(value) == -1 && value.compareTo(new BigInteger(Long.toString(Long.MAX_VALUE))) == -1;
				if (isLong) {
					return Long.parseLong(hexNumberString.substring(2), 16);
				} else {
					return value;
				}
			}
		}
	}
}
 
Example 6
private BigInteger getMaximumMegabytes(BigInteger currentMaximum, JsonNode formatNode) {
    if (formatNode.path(JSONConstants.MAXIMUM_MEGABYTES).isNumber()) {
        BigInteger value = formatNode.path(JSONConstants.MAXIMUM_MEGABYTES).bigIntegerValue();
        if (currentMaximum == null || currentMaximum.compareTo(value) > 0) {
            return value;
        }
    }
    return currentMaximum;
}
 
Example 7
String getIPv6Address() {
    if (BuildConfig.DEBUG) 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 8
@Override
public HdPublicKey cKDpub(final int index) {
    if (isHardened(index)) {
        return null;
    }

    final HdKey parent = this.hdKey;
    final byte[] kPar = parent.getKey();

    final byte[] data = new byte[37];
    final ByteArrayWriter writer = new ByteArrayWriter(data);
    writer.concat(kPar, 33);
    writer.concatSer32(index);

    final byte[] I = Digest.hmacSha512(parent.getChainCode(), data);
    final byte[] Il = head32(I);
    final byte[] Ir = tail32(I);

    final BigInteger parse256_Il = parse256(Il);
    final ECPoint ki = gMultiplyAndAddPoint(parse256_Il, kPar);

    if (parse256_Il.compareTo(n()) >= 0 || ki.isInfinity()) {
        return cKDpub(index + 1);
    }

    final byte[] key = pointSerP(ki);

    return new HdPublicKey(new HdKey.Builder()
            .network(parent.getNetwork())
            .neutered(true)
            .depth(parent.depth() + 1)
            .parentFingerprint(parent.calculateFingerPrint())
            .key(key)
            .chainCode(Ir)
            .childNumber(index)
            .build());
}
 
Example 9
Source Project: Bytecoder   File: DSAKeyPairGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate the private key component of the key pair using the
 * provided source of random bits. This method uses the random but
 * source passed to generate a seed and then calls the seed-based
 * generateX method.
 */
private BigInteger generateX(SecureRandom random, BigInteger q) {
    BigInteger x = null;
    byte[] temp = new byte[qlen];
    while (true) {
        random.nextBytes(temp);
        x = new BigInteger(1, temp).mod(q);
        if (x.signum() > 0 && (x.compareTo(q) < 0)) {
            return x;
        }
    }
}
 
Example 10
public SecP384R1FieldElement(BigInteger x)
{
    if (x == null || x.signum() < 0 || x.compareTo(Q) >= 0)
    {
        throw new IllegalArgumentException("x value invalid for SecP384R1FieldElement");
    }

    this.x = SecP384R1Field.fromBigInteger(x);
}
 
Example 11
private static void checkKeyPair(KeyPair kp, Sizes modulusSize,
        Sizes exponentSize) throws Exception {

    System.out.println("Checking (" + modulusSize + ", " +
        exponentSize + ")");
    DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
    BigInteger p = privateKey.getParams().getP();
    BigInteger x = privateKey.getX();

    if (p.bitLength() != modulusSize.getIntSize()) {
        throw new Exception("Invalid modulus size: " + p.bitLength());
    }

    if (x.bitLength() > exponentSize.getIntSize()) {
        throw new Exception("X has more bits than expected: " +
            x.bitLength());
    }

    BigInteger pMinus2 =
        p.subtract(BigInteger.ONE).subtract(BigInteger.ONE);

    if ((x.compareTo(BigInteger.ONE) < 0 ||
            (x.compareTo(pMinus2)) > 0)) {
        throw new Exception(
            "X outside range 1<=x<p-2:  x: " + x + " p: " + p);
    }
}
 
Example 12
BigInteger montgomeryMultiply(BigInteger a, BigInteger b, BigInteger N,
        int len, BigInteger n_prime)
        throws Throwable {
    BigInteger T = a.multiply(b);
    BigInteger R = BigInteger.ONE.shiftLeft(len*32);
    BigInteger mask = R.subtract(BigInteger.ONE);
    BigInteger m = (T.and(mask)).multiply(n_prime);
    m = m.and(mask); // i.e. m.mod(R)
    T = T.add(m.multiply(N));
    T = T.shiftRight(len*32); // i.e. T.divide(R)
    if (T.compareTo(N) > 0) {
        T = T.subtract(N);
    }
    return T;
}
 
Example 13
/**
 * Return <code>true</code> if <code>val</code> is square free.
 * 
 * @param val
 * @return
 */
public static boolean isSquareFree(BigInteger val) {
	if (val.compareTo(BigInteger.ZERO) < 0) {
		val = val.negate();
	}
	SortedMap<BigInteger, Integer> map = new SquareFreeTreedMap();
	try {
		factorInteger(val, map);
		return true;
	} catch (ReturnException re) {
	}
	return false;
}
 
Example 14
Source Project: nuls-v2   File: ContractTokenBalanceManager.java    License: MIT License 5 votes vote down vote up
public Result subtractContractToken(String account, String contract, BigInteger token) {
    tokenLock.lock();
    try {
        Map<String, ContractTokenInfo> tokens = contractTokenOfLocalAccount.get(account);
        if (tokens == null) {
            return getSuccess();
        } else {
            ContractTokenInfo info = tokens.get(contract);
            if (info == null) {
                return getSuccess();
            }
            BigInteger currentToken = info.getAmount();
            if (currentToken == null) {
                return getSuccess();
            } else {
                if (currentToken.compareTo(token) < 0) {
                    return Result.getFailed(ContractErrorCode.INSUFFICIENT_TOKEN_BALANCE);
                }
                currentToken = currentToken.subtract(token);
                tokens.put(contract, info.setAmount(currentToken));
            }
        }
        return getSuccess();
    } finally {
        tokenLock.unlock();
    }
}
 
Example 15
private static void testCmpPow52(FDBigInteger t, int p5, int p2) throws Exception {
    FDBigInteger o = FDBigInteger.valueOfPow52(p5, p2);
    BigInteger bt = t.toBigInteger();
    BigInteger bo = biPow52(p5, p2);
    int cmp = t.cmp(o);
    int bcmp = bt.compareTo(bo);
    if (bcmp != cmp) {
        throw new Exception("cmpPow52 returns " + cmp + " expected " + bcmp);
    }
    check(bt, t, "cmpPow52 corrupts this");
    check(bo, o, "cmpPow5 corrupts other");
}
 
Example 16
Source Project: web3j   File: JsonRpc2_0Rx.java    License: Apache License 2.0 5 votes vote down vote up
private Flowable<EthBlock> replayPastBlocksFlowableSync(
        DefaultBlockParameter startBlock,
        boolean fullTransactionObjects,
        Flowable<EthBlock> onCompleteFlowable) {

    BigInteger startBlockNumber;
    BigInteger latestBlockNumber;
    try {
        startBlockNumber = getBlockNumber(startBlock);
        latestBlockNumber = getLatestBlockNumber();
    } catch (IOException e) {
        return Flowable.error(e);
    }

    if (startBlockNumber.compareTo(latestBlockNumber) > -1) {
        return onCompleteFlowable;
    } else {
        return Flowable.concat(
                replayBlocksFlowableSync(
                        new DefaultBlockParameterNumber(startBlockNumber),
                        new DefaultBlockParameterNumber(latestBlockNumber),
                        fullTransactionObjects),
                Flowable.defer(
                        () ->
                                replayPastBlocksFlowableSync(
                                        new DefaultBlockParameterNumber(
                                                latestBlockNumber.add(BigInteger.ONE)),
                                        fullTransactionObjects,
                                        onCompleteFlowable)));
    }
}
 
Example 17
Source Project: protect   File: BNField2.java    License: MIT License 5 votes vote down vote up
public BNField2 add(BigInteger v) {
	BigInteger s = re.add(v);
	if (docount && re.bitLength() > SMALLSIZE && v.bitLength() > SMALLSIZE) {
		addcount++;
	}
	if (s.compareTo(bn.p) >= 0) {
		s = s.subtract(bn.p);
	}
	return new BNField2(bn, s, im, false);
}
 
Example 18
public static void modInv(int order) {
    int failCount = 0, successCount = 0, nonInvCount = 0;

    for (int i=0; i<SIZE; i++) {
        BigInteger x = fetchNumber(order);
        while(x.equals(BigInteger.ZERO))
            x = fetchNumber(order);
        BigInteger m = fetchNumber(order).abs();
        while(m.compareTo(BigInteger.ONE) != 1)
            m = fetchNumber(order).abs();

        try {
            BigInteger inv = x.modInverse(m);
            BigInteger prod = inv.multiply(x).remainder(m);

            if (prod.signum() == -1)
                prod = prod.add(m);

            if (prod.equals(BigInteger.ONE))
                successCount++;
            else
                failCount++;
        } catch(ArithmeticException e) {
            nonInvCount++;
        }
    }
    report("Modular Inverse for " + order + " bits", failCount);
}
 
Example 19
Source Project: RipplePower   File: Transaction.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * Verify the transaction structure as follows
 * </p>
 * <ul>
 * <li>A transaction must have at least one input and one output</li>
 * <li>A transaction output may not specify a negative number of coins</li>
 * <li>The sum of all of the output amounts must not exceed 21,000,000
 * BTC</li>
 * <li>A non-coinbase transaction may not contain any unconnected
 * inputs</li>
 * <li>A connected output may not be used by more than one input</li>
 * <li>The input script must contain only push-data operations</li>
 * </ul>
 *
 * @param canonical
 *            TRUE to enforce canonical transactions
 * @throws VerificationException
 *             Script verification failed
 */
public void verify(boolean canonical) throws VerificationException {
	try {
		// Must have at least one input and one output
		if (txInputs.isEmpty() || txOutputs.isEmpty())
			throw new VerificationException("Transaction does not have at least 1 input and 1 output",
					RejectMessage.REJECT_INVALID, txHash);
		// No output value may be negative
		// Sum of all output values must not exceed MAX_MONEY
		BigInteger outTotal = BigInteger.ZERO;
		for (TransactionOutput txOut : txOutputs) {
			BigInteger outValue = txOut.getValue();
			if (outValue.signum() < 0)
				throw new VerificationException("Transaction output value is negative",
						RejectMessage.REJECT_INVALID, txHash);
			outTotal = outTotal.add(outValue);
			if (outTotal.compareTo(NetParams.MAX_MONEY) > 0)
				throw new VerificationException("Total transaction output amount exceeds maximum",
						RejectMessage.REJECT_INVALID, txHash);
			// byte[] scriptBytes = txOut.getScriptBytes();
		}
		if (!coinBase) {
			// All inputs must have connected outputs
			// No outpoint may be used more than once
			// Input scripts must consist of only push-data operations
			List<OutPoint> outPoints = new ArrayList<>(txInputs.size());
			for (TransactionInput txIn : txInputs) {
				OutPoint outPoint = txIn.getOutPoint();
				if (outPoint.getHash().equals(Sha256Hash.ZERO_HASH) || outPoint.getIndex() < 0)
					throw new VerificationException("Non-coinbase transaction contains unconnected inputs",
							RejectMessage.REJECT_INVALID, txHash);
				if (outPoints.contains(outPoint))
					throw new VerificationException("Connected output used in multiple inputs",
							RejectMessage.REJECT_INVALID, txHash);
				outPoints.add(outPoint);
				if (canonical) {
					if (!Script.checkInputScript(txIn.getScriptBytes()))
						throw new VerificationException(
								"Input script must contain only canonical push-data operations",
								RejectMessage.REJECT_NONSTANDARD, txHash);
				}
			}
		}
	} catch (EOFException exc) {
		throw new VerificationException("End-of-data while processing script", RejectMessage.REJECT_MALFORMED,
				txHash);
	}
}
 
Example 20
Source Project: bitherj   File: Block.java    License: Apache License 2.0 4 votes vote down vote up
public void verifyDifficultyFromPreviousBlock(Block prev, int transitionTime) {
        // checkState(lock.isHeldByCurrentThread());

        // Is this supposed to be a difficulty transition point?
        if ((prev.getBlockNo() + 1) % BitherjSettings.BLOCK_DIFFICULTY_INTERVAL != 0) {

            // TODO: Refactor this hack after 0.5 is released and we stop supporting deserialization compatibility.
            // This should be a method of the NetworkParameters, which should in turn be using singletons and a subclass
            // for each network type. Then each network can define its own difficulty transition rules.
//            if (Settings.params.getId().equals(NetworkParameters.ID_TESTNET) && nextBlock.getTime().after(testnetDiffDate)) {
//                checkTestnetDifficulty(storedPrev, prev, nextBlock);
//                return;
//            }

            // No ... so check the difficulty didn't actually change.
            if (this.getBlockBits() != prev.getBlockBits())
                throw new VerificationException("Unexpected change in difficulty at height " + prev.getBlockNo() +
                        ": " + Long.toHexString(this.getBlockBits()) + " vs " +
                        Long.toHexString(prev.getBlockBits()));
            return;
        }

        // We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every
        // two weeks after the initial block chain download.
//        long now = System.currentTimeMillis();
//        Block cursor = get(prev.getBlockHash());
//        for (int i = 0; i < BitherjSettings.BLOCK_DIFFICULTY_INTERVAL - 1; i++) {
//            if (cursor == null) {
//                // This should never happen. If it does, it means we are following an incorrect or busted chain.
//                throw new VerificationException(
//                        "Difficulty transition point but we did not find a way back to the genesis block.");
//            }
//            cursor = get(cursor.getBlockPrev());
//        }
//        long elapsed = System.currentTimeMillis() - now;
//        if (elapsed > 50)
//            log.info("Difficulty transition traversal took {}msec", elapsed);
//
//        Block blockIntervalAgo = cursor;
//        int timespan = (int) (prev.getBlockTime() - blockIntervalAgo.getBlockTime());
        int timespan = (int) (prev.getBlockTime() - transitionTime);
        // Limit the adjustment step.
        final int targetTimespan = BitherjSettings.TARGET_TIMESPAN;
        if (timespan < targetTimespan / 4)
            timespan = targetTimespan / 4;
        if (timespan > targetTimespan * 4)
            timespan = targetTimespan * 4;

        BigInteger newDifficulty = Utils.decodeCompactBits(prev.getBlockBits());
        newDifficulty = newDifficulty.multiply(BigInteger.valueOf(timespan));
        newDifficulty = newDifficulty.divide(BigInteger.valueOf(targetTimespan));

        if (newDifficulty.compareTo(BitherjSettings.proofOfWorkLimit) > 0) {
            // log.info("Difficulty hit proof of work limit: {}", newDifficulty.toString(16));
            newDifficulty = BitherjSettings.proofOfWorkLimit;
        }

        int accuracyBytes = (int) (this.getBlockBits() >>> 24) - 3;
        BigInteger receivedDifficulty = this.getDifficultyTargetAsInteger();

        // The calculated difficulty is to a higher precision than received, so reduce here.
        BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8);
        newDifficulty = newDifficulty.and(mask);

        if (newDifficulty.compareTo(receivedDifficulty) != 0)
            throw new VerificationException("Network provided difficulty bits do not match what was calculated: " +
                    receivedDifficulty.toString(16) + " vs " + newDifficulty.toString(16));
    }