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

The following examples show how to use java.math.BigInteger#multiply() . 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: coming   File: Math_79_MathUtils_s.java    License: MIT License 6 votes vote down vote up
/**
 * Raise a BigInteger to a long power.
 * @param k number to raise
 * @param e exponent (must be positive or null)
 * @return k<sup>e</sup>
 * @exception IllegalArgumentException if e is negative
 */
public static BigInteger pow(final BigInteger k, long e)
    throws IllegalArgumentException {

    if (e < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            "cannot raise an integral value to a negative power ({0}^{1})",
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (e != 0) {
        if ((e & 0x1) != 0) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e >> 1;
    }

    return result;

}
 
Example 2
Source Project: astor   File: MathUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Raise a BigInteger to a long power.
 *
 * @param k Number to raise.
 * @param e Exponent (must be positive or zero).
 * @return k<sup>e</sup>
 * @throws NotPositiveException if {@code e < 0}.
 */
public static BigInteger pow(final BigInteger k, long e) {
    if (e < 0) {
        throw new NotPositiveException(LocalizedFormats.EXPONENT, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (e != 0) {
        if ((e & 0x1) != 0) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e >> 1;
    }

    return result;

}
 
Example 3
Source Project: j2objc   File: BigIntegerMultiplyTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Multiply two negative numbers of the same length
 */
public void testCase1() {
    byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3};
    byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30};
    int aSign = -1;
    int bSign = -1;        
    byte rBytes[] = {10, 40, 100, -55, 96, 51, 76, 40, -45, 85, 105, 4, 28, -86, -117, -52, 100, 120, 90};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.multiply(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for(int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}
 
Example 4
Source Project: ripple-lib-java   File: NaccacheSternEngine.java    License: ISC License 6 votes vote down vote up
/**
 * Computes the integer x that is expressed through the given primes and the
 * congruences with the chinese remainder theorem (CRT).
 * 
 * @param congruences
 *            the congruences c_i
 * @param primes
 *            the primes p_i
 * @return an integer x for that x % p_i == c_i
 */
private static BigInteger chineseRemainder(Vector congruences, Vector primes)
{
    BigInteger retval = ZERO;
    BigInteger all = ONE;
    for (int i = 0; i < primes.size(); i++)
    {
        all = all.multiply((BigInteger)primes.elementAt(i));
    }
    for (int i = 0; i < primes.size(); i++)
    {
        BigInteger a = (BigInteger)primes.elementAt(i);
        BigInteger b = all.divide(a);
        BigInteger b_ = b.modInverse(a);
        BigInteger tmp = b.multiply(b_);
        tmp = tmp.multiply((BigInteger)congruences.elementAt(i));
        retval = retval.add(tmp);
    }

    return retval.mod(all);
}
 
Example 5
Source Project: astor   File: MathUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Raise a BigInteger to a long power.
 * @param k number to raise
 * @param e exponent (must be positive or null)
 * @return k<sup>e</sup>
 * @exception IllegalArgumentException if e is negative
 */
public static BigInteger pow(final BigInteger k, long e)
    throws IllegalArgumentException {

    if (e < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            "cannot raise an integral value to a negative power ({0}^{1})",
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (e != 0) {
        if ((e & 0x1) != 0) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e >> 1;
    }

    return result;

}
 
Example 6
Source Project: nuls   File: SimpleToken.java    License: MIT License 5 votes vote down vote up
public SimpleToken(@Required String name, @Required String symbol, @Required BigInteger initialAmount, @Required int decimals) {
    this.name = name;
    this.symbol = symbol;
    this.decimals = decimals;
    totalSupply = initialAmount.multiply(BigInteger.TEN.pow(decimals));;
    balances.put(Msg.sender(), totalSupply);
    emit(new TransferEvent(null, Msg.sender(), totalSupply));
}
 
Example 7
/**
 * Simple series expansion for exp(x).
 * The convergence criterion works only for |x|<=1, so it should not be called directly, only via one of the reduction formulas.
 */
private static BigDecimal expSeriesExpansion(BigDecimal x, Scale outScale) {
    // get demanded precision and compute the series limit for it:
	// for large arguments, the series doesn't converge so quickly,
	// we have to add extra precision...
	int xMag = Magnitude.of(x);
	if (xMag < 0) xMag = 0; // do not reduce precision if magnitude is < 0
	Scale errorScale = outScale.add(xMag);
       BigDecimal maxErr = errorScale.getErrorBound();
       if (DEBUG) LOG.debug("outScale=" + outScale + ", errorScale=" + errorScale + ", maxErr=" + maxErr);
    
    // calculate series expansion:
       BigDecimal r = F_1;
    BigDecimal xpow = F_1;
    BigInteger iFac = I_1;
    int i=1;
    BigDecimal elem;
    Scale internalScale = errorScale.add(1);
    do {
        xpow = internalScale.applyTo(xpow.multiply(x)); // x^i
        iFac = iFac.multiply(BigInteger.valueOf(i)); // i!
        if (DEBUG) LOG.debug("i=" + i + ", iFac=" + iFac);
        elem = BigDecimalMath.divide(xpow, iFac, internalScale);
        r = r.add(elem);
        if (DEBUG) LOG.debug("exp(" + x + ")[" + i + "] = " + r);
        i++;
    // stop if the error is smaller than allowed:
    } while (elem.abs().compareTo(maxErr) > 0);
    
    if (DEBUG) LOG.debug("exp(" + x + ") = " + r);
    return outScale.applyTo(r);
}
 
Example 8
private static void testMultiply() {
    System.out.println("Testing BigInteger.multiply");
    int py = 2000;
    int px = Integer.MAX_VALUE - py;
    BigInteger x = BigInteger.ONE.shiftLeft(px);
    BigInteger y = BigInteger.ONE.shiftLeft(py);
    try {
        BigInteger actual = x.multiply(y);
        throw new RuntimeException("(1 << " + px + " ) * (1 << " + py + ").bitLength()=" + actual.bitLength());
    } catch (ArithmeticException e) {
        // expected
    }
}
 
Example 9
public void testNanoTime() throws Exception {
    String name = "name";
    DiagnosticCommand arg = new DiagnosticCommand(name,
            "desc", DiagnosticArgumentType.NANOTIME,
            false, "0");
    DiagnosticCommand[] args = {arg};

    BigInteger bi = new BigInteger("7");
    //These should work
    parse(name, bi.toString(), name + "=7ns", args);

    bi = bi.multiply(BigInteger.valueOf(1000));
    parse(name, bi.toString(), name + "=7us", args);

    bi = bi.multiply(BigInteger.valueOf(1000));
    parse(name, bi.toString(), name + "=7ms", args);

    bi = bi.multiply(BigInteger.valueOf(1000));
    parse(name, bi.toString(), name + "=7s", args);

    bi = bi.multiply(BigInteger.valueOf(60));
    parse(name, bi.toString() , name + "=7m", args);

    bi = bi.multiply(BigInteger.valueOf(60));
    parse(name, bi.toString() , name + "=7h", args);

    bi = bi.multiply(BigInteger.valueOf(24));
    parse(name, bi.toString() , name + "=7d", args);

    parse(name, "0", name + "=0", args);

    shouldFail(name + "=7xs", args);
    shouldFail(name + "=7mms", args);
    shouldFail(name + "=7f", args);
    //Currently, only value 0 is allowed without unit
    shouldFail(name + "=7", args);
}
 
Example 10
@Test
public void testDoubleValueForLargeNumeratorAndDenominator() {
    final BigInteger pow400 = BigInteger.TEN.pow(400);
    final BigInteger pow401 = BigInteger.TEN.pow(401);
    final BigInteger two = new BigInteger("2");
    final BigFraction large = new BigFraction(pow401.add(BigInteger.ONE),
                                              pow400.multiply(two));

    Assert.assertEquals(5, large.doubleValue(), 1e-15);
}
 
Example 11
Source Project: TencentKona-8   File: DSA.java    License: GNU General Public License v2.0 5 votes vote down vote up
private BigInteger generateV(BigInteger y, BigInteger p,
         BigInteger q, BigInteger g, BigInteger w, BigInteger r)
         throws SignatureException {

    byte[] s2;
    try {
        s2 = md.digest();
    } catch (RuntimeException re) {
        // Only for RawDSA due to its 20-byte length restriction
        throw new SignatureException(re.getMessage());
    }
    // get the leftmost min(N, outLen) bits of the digest value
    int nBytes = q.bitLength()/8;
    if (nBytes < s2.length) {
        s2 = Arrays.copyOfRange(s2, 0, nBytes);
    }
    BigInteger z = new BigInteger(1, s2);

    BigInteger u1 = z.multiply(w).mod(q);
    BigInteger u2 = (r.multiply(w)).mod(q);

    BigInteger t1 = g.modPow(u1,p);
    BigInteger t2 = y.modPow(u2,p);
    BigInteger t3 = t1.multiply(t2);
    BigInteger t5 = t3.mod(p);
    return t5.mod(q);
}
 
Example 12
Source Project: astor   File: FastMathTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testMultiplyExactLong() {
    long[] specialValues = new long[] {
        Long.MIN_VALUE, Long.MIN_VALUE + 1, Long.MIN_VALUE + 2,
        Long.MAX_VALUE, Long.MAX_VALUE - 1, Long.MAX_VALUE - 2,
        -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
        -1 - (Long.MIN_VALUE / 2), 0 - (Long.MIN_VALUE / 2), 1 - (Long.MIN_VALUE / 2),
        -1 + (Long.MAX_VALUE / 2), 0 + (Long.MAX_VALUE / 2), 1 + (Long.MAX_VALUE / 2),
    };
    for (long a : specialValues) {
        for (long b : specialValues) {
            BigInteger bdA   = BigInteger.valueOf(a);
            BigInteger bdB   = BigInteger.valueOf(b);
            BigInteger bdMul = bdA.multiply(bdB);
            if (bdMul.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0 ||
                    bdMul.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
                try {
                    FastMath.multiplyExact(a, b);
                    Assert.fail("an exception should have been thrown " + a + b);
                } catch (MathArithmeticException mae) {
                    // expected
                }
            } else {
                Assert.assertEquals(bdMul, BigInteger.valueOf(FastMath.multiplyExact(a, b)));
            }
        }
    }
}
 
Example 13
Source Project: hipparchus   File: FastMathTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiplyExactInt() {
    int[] specialValues = new int[] {
        Integer.MIN_VALUE, Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 2,
        Integer.MAX_VALUE, Integer.MAX_VALUE - 1, Integer.MAX_VALUE - 2,
        -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
        -1 - (Integer.MIN_VALUE / 2), 0 - (Integer.MIN_VALUE / 2), 1 - (Integer.MIN_VALUE / 2),
        -1 + (Integer.MAX_VALUE / 2), 0 + (Integer.MAX_VALUE / 2), 1 + (Integer.MAX_VALUE / 2),
    };
    for (int a : specialValues) {
        for (int b : specialValues) {
            BigInteger bdA   = BigInteger.valueOf(a);
            BigInteger bdB   = BigInteger.valueOf(b);
            BigInteger bdMul = bdA.multiply(bdB);
            if (bdMul.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0 ||
                bdMul.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
                try {
                    FastMath.multiplyExact(a, b);
                    fail("an exception should have been thrown " + a + b);
                } catch (MathRuntimeException mae) {
                    // expected
                }
            } else {
                assertEquals(bdMul, BigInteger.valueOf(FastMath.multiplyExact(a, b)));
            }
        }
    }
}
 
Example 14
public BigInteger calcNumSequences() {
	BigInteger numSequences = BigInteger.ZERO;
	for (SimpleConfSpace.Position pos : positions) {
		BigInteger numResTypes = BigInteger.valueOf(pos.resFlex.resTypes.size());
		if (MathTools.isZero(numSequences)) {
			numSequences = numResTypes;
		} else {
			numSequences = numSequences.multiply(numResTypes);
		}
	}
	return numSequences;
}
 
Example 15
Source Project: jdk8u60   File: DSA.java    License: GNU General Public License v2.0 5 votes vote down vote up
private BigInteger generateV(BigInteger y, BigInteger p,
         BigInteger q, BigInteger g, BigInteger w, BigInteger r)
         throws SignatureException {

    byte[] s2;
    try {
        s2 = md.digest();
    } catch (RuntimeException re) {
        // Only for RawDSA due to its 20-byte length restriction
        throw new SignatureException(re.getMessage());
    }
    // get the leftmost min(N, outLen) bits of the digest value
    int nBytes = q.bitLength()/8;
    if (nBytes < s2.length) {
        s2 = Arrays.copyOfRange(s2, 0, nBytes);
    }
    BigInteger z = new BigInteger(1, s2);

    BigInteger u1 = z.multiply(w).mod(q);
    BigInteger u2 = (r.multiply(w)).mod(q);

    BigInteger t1 = g.modPow(u1,p);
    BigInteger t2 = y.modPow(u2,p);
    BigInteger t3 = t1.multiply(t2);
    BigInteger t5 = t3.mod(p);
    return t5.mod(q);
}
 
Example 16
/**
 * A000197 or what I call the "inverse hyperfactorial" is the product
 * 1^n*2^(n-1)*..*(n-1)^2*n^1 = 1!*2!*3!*...(n-1)!*n!.
 * @param n
 * @return the "inverse hyperfactorial" of n aka 1!*2!*3!*...(n-1)!*n!
 */
public static BigInteger inverse(int n) {
	BigInteger result = I_1;
	BigInteger kFactorial = I_1;
	for (int k=2; k<=n; k++) {
		kFactorial = kFactorial.multiply(BigInteger.valueOf(k));
		result = result.multiply(kFactorial);
	}
	return result;
}
 
Example 17
Source Project: protect   File: RsaSharing.java    License: MIT License 4 votes vote down vote up
public static RsaSharing generateSharing(final int keySizeBits, final int numServers, final int threshold) throws InvalidKeySpecException, NoSuchAlgorithmException {

		final int primeLength = (keySizeBits / 2);
		
		System.out.print("  Generating p...");
		final BigInteger p = Primes.generateSafePrime(primeLength);
		final BigInteger pPrime = Primes.getSophieGermainPrime(p);
		System.out.println(" done.");

		System.out.print("  Generating q...");
		final BigInteger q = Primes.generateSafePrime(primeLength);
		final BigInteger qPrime = Primes.getSophieGermainPrime(q);
		System.out.println(" done.");

		System.out.print("  Computing moduli...");
		final BigInteger m = pPrime.multiply(qPrime);
		final BigInteger n = p.multiply(q);
		System.out.println(" done.");

		// Public exponent (e must be greater than numServers)
		final BigInteger e = BigInteger.valueOf(65537);
		if (e.longValue() <= numServers) {
			throw new IllegalArgumentException("e must be greater than the number of servers!");
		}

		// Create standard RSA Public key pair
		System.out.print("  Creating RSA keypair...");
		final RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(n, e);
		final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		final RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);

		// Create standard RSA Private key
		final BigInteger totient = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
		final BigInteger realD = Exponentiation.modInverse(e, totient);
		final RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(n, realD);
		final RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
		System.out.println(" done.");

		// Create secret shares of "d"
		System.out.print("  Generating secret shares...");
		final BigInteger d = Exponentiation.modInverse(e, m);

		// Generate random polynomial coefficients for secret sharing of d
		final BigInteger[] coefficients = RandomNumberGenerator.generateRandomArray(threshold, m);

		// Set the secret as the first coefficient
		coefficients[0] = d;

		// Evaluate the polynomial from 1 to numSevers (must not evaluate at zero!)
		final ShamirShare[] shares = new ShamirShare[numServers];
		for (int i = 0; i < numServers; i++) {
			BigInteger xCoord = BigInteger.valueOf(i + 1);
			shares[i] = Polynomials.evaluatePolynomial(coefficients, xCoord, m);
		}
		System.out.println(" done.");

		// Generate public and private verification keys
		System.out.print("  Creating public and private verification keys...");

		// Generate public verification key v as a random square modulo n
		final BigInteger sqrtV = RandomNumberGenerator.generateRandomInteger(n);
		final BigInteger v = sqrtV.modPow(ThresholdSignatures.TWO, n);

		// Generate private verification keys as v^share mod n
		final BigInteger[] verificationKeys = new BigInteger[shares.length];
		for (int i = 0; i < shares.length; i++) {
			verificationKeys[i] = v.modPow(shares[i].getY(), n);
		}
		System.out.println(" done.");

		return new RsaSharing(numServers, threshold, publicKey, privateKey, shares, v, verificationKeys);
	}
 
Example 18
Source Project: AVM   File: BigIntegerTarget.java    License: MIT License 4 votes vote down vote up
@Callable
public static byte[] multiply(byte[] val) {
    BigInteger testValue = new BigInteger(val);
    BigInteger result = testValue.multiply(testValue);
    return result.toByteArray();
}
 
Example 19
public static BigInteger new_multiply(BigInteger op1, BigInteger op2) {
  return op1.multiply(op2);
}
 
Example 20
Source Project: lams   File: OpMultiply.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Implements the {@code multiply} operator directly here for certain types
 * of supported operands and otherwise delegates to any registered overloader
 * for types not supported here.
 * <p>Supported operand types:
 * <ul>
 * <li>numbers
 * <li>String and int ('abc' * 2 == 'abcabc')
 * </ul>
 */
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
	Object leftOperand = getLeftOperand().getValueInternal(state).getValue();
	Object rightOperand = getRightOperand().getValueInternal(state).getValue();

	if (leftOperand instanceof Number && rightOperand instanceof Number) {
		Number leftNumber = (Number) leftOperand;
		Number rightNumber = (Number) rightOperand;

		if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) {
			BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
			BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
			return new TypedValue(leftBigDecimal.multiply(rightBigDecimal));
		}
		else if (leftNumber instanceof Double || rightNumber instanceof Double) {
			this.exitTypeDescriptor = "D";
			return new TypedValue(leftNumber.doubleValue() * rightNumber.doubleValue());
		}
		else if (leftNumber instanceof Float || rightNumber instanceof Float) {
			this.exitTypeDescriptor = "F";
			return new TypedValue(leftNumber.floatValue() * rightNumber.floatValue());
		}
		else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger) {
			BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
			BigInteger rightBigInteger = NumberUtils.convertNumberToTargetClass(rightNumber, BigInteger.class);
			return new TypedValue(leftBigInteger.multiply(rightBigInteger));
		}
		else if (leftNumber instanceof Long || rightNumber instanceof Long) {
			this.exitTypeDescriptor = "J";
			return new TypedValue(leftNumber.longValue() * rightNumber.longValue());
		}
		else if (CodeFlow.isIntegerForNumericOp(leftNumber) || CodeFlow.isIntegerForNumericOp(rightNumber)) {
			this.exitTypeDescriptor = "I";
			return new TypedValue(leftNumber.intValue() * rightNumber.intValue());
		}
		else {
			// Unknown Number subtypes -> best guess is double multiplication
			return new TypedValue(leftNumber.doubleValue() * rightNumber.doubleValue());
		}
	}

	if (leftOperand instanceof String && rightOperand instanceof Integer) {
		int repeats = (Integer) rightOperand;
		StringBuilder result = new StringBuilder();
		for (int i = 0; i < repeats; i++) {
			result.append(leftOperand);
		}
		return new TypedValue(result.toString());
	}

	return state.operate(Operation.MULTIPLY, leftOperand, rightOperand);
}