protected BigInteger modReduce(BigInteger x) { if (r != null) { boolean negative = x.signum() < 0; if (negative) { x = x.abs(); } int qLen = q.bitLength(); boolean rIsOne = r.equals(ECConstants.ONE); while (x.bitLength() > (qLen + 1)) { BigInteger u = x.shiftRight(qLen); BigInteger v = x.subtract(u.shiftLeft(qLen)); if (!rIsOne) { u = u.multiply(r); } x = u.add(v); } while (x.compareTo(q) >= 0) { x = x.subtract(q); } if (negative && x.signum() != 0) { x = q.subtract(x); } } else { x = x.mod(q); } return x; }
@Test public void testCheckFunctions() { assertFalse(ArbitraryInteger.ZERO.isNegativ()); assertTrue(ArbitraryInteger.ZERO.isZero()); assertFalse(ArbitraryInteger.ZERO.isPositiv()); assertEquals(0, ArbitraryInteger.ZERO.signum()); assertFalse(ArbitraryInteger.ONE.isNegativ()); assertFalse(ArbitraryInteger.ONE.isZero()); assertTrue(ArbitraryInteger.ONE.isPositiv()); assertEquals(1, ArbitraryInteger.ONE.signum()); assertTrue(ArbitraryInteger.MINUS_ONE.isNegativ()); assertFalse(ArbitraryInteger.MINUS_ONE.isZero()); assertFalse(ArbitraryInteger.MINUS_ONE.isPositiv()); assertEquals(-1, ArbitraryInteger.MINUS_ONE.signum()); for (int i = 0; i < this.iterations; i++) { BigInteger reference = BigInteger.valueOf(this.randomizer.nextLong() - Long.MAX_VALUE) .pow(this.randomizer.nextInt(20) + 10); ArbitraryInteger proband = ArbitraryInteger.valueOf(reference.toByteArray()); assertEquals(reference.signum(), proband.signum()); assertTrue( reference.signum() < 0 && proband.isNegativ() || reference.signum() > 0 && !proband.isNegativ()); assertTrue( reference.signum() > 0 && proband.isPositiv() || reference.signum() < 0 && !proband.isPositiv()); assertTrue(reference.bitLength() == proband.bitLength()); } }
/** @tests java.math.BigInteger#signum() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "signum", args = {}) public void test_signum() { assertTrue("Wrong positive signum", two.signum() == 1); assertTrue("Wrong zero signum", zero.signum() == 0); assertTrue("Wrong neg zero signum", zero.negate().signum() == 0); assertTrue("Wrong neg signum", two.negate().signum() == -1); }
/** * Constructs a new BigFraction from two BigDecimals. * * @throws ArithemeticException if denominator == 0. */ private static BigFraction valueOfHelper( final BigDecimal numerator, final BigDecimal denominator) { // Note: Cannot use .equals(BigDecimal.ZERO), because "0.00" != "0.0". if (denominator.unscaledValue().equals(BigInteger.ZERO)) { throw new ArithmeticException("Divide by zero: fraction denominator is zero."); } // Format of BigDecimal: unscaled / 10^scale BigInteger tmpNumerator = numerator.unscaledValue(); BigInteger tmpDenominator = denominator.unscaledValue(); // (u1/10^s1) / (u2/10^s2) = u1 / (u2 * 10^(s1-s2)) = (u1 * 10^(s2-s1)) // / u2 if (numerator.scale() > denominator.scale()) { tmpDenominator = tmpDenominator.multiply(BigInteger.TEN.pow(numerator.scale() - denominator.scale())); } else if (numerator.scale() < denominator.scale()) { tmpNumerator = tmpNumerator.multiply(BigInteger.TEN.pow(denominator.scale() - numerator.scale())); // else: scales are equal, do nothing. } final BigInteger gcd = tmpNumerator.gcd(tmpDenominator); tmpNumerator = tmpNumerator.divide(gcd); tmpDenominator = tmpDenominator.divide(gcd); if (tmpDenominator.signum() < 0) { tmpNumerator = tmpNumerator.negate(); tmpDenominator = tmpDenominator.negate(); } return new BigFraction(tmpNumerator, tmpDenominator, Reduced.YES); }
public FpFieldElement(BigInteger q, BigInteger x) { if ((x == null) || (x.signum() < 0) || (x.compareTo(q) >= 0)) { throw new IllegalArgumentException("x value invalid in Fp field element"); } this.q = q; this.x = x; }
public static void shift(int order) { int failCount1 = 0; int failCount2 = 0; int failCount3 = 0; for (int i = 0; i < 100; i++) { BigInteger x = fetchNumber(order); int n = Math.abs(rnd.nextInt() % 200); if (!x.shiftLeft(n).equals(x.multiply(BigInteger.valueOf(2L).pow(n)))) failCount1++; BigInteger y[] = x.divideAndRemainder(BigInteger.valueOf(2L).pow(n)); BigInteger z = (x.signum() < 0 && y[1].signum() != 0 ? y[0].subtract(BigInteger.ONE) : y[0]); BigInteger b = x.shiftRight(n); if (!b.equals(z)) { System.err.println("Input is " + x.toString(2)); System.err.println("shift is " + n); System.err.println("Divided " + z.toString(2)); System.err.println("Shifted is " + b.toString(2)); if (b.toString().equals(z.toString())) System.err.println("Houston, we have a problem."); failCount2++; } if (!x.shiftLeft(n).shiftRight(n).equals(x)) failCount3++; } report("baz shiftLeft", failCount1); report("baz shiftRight", failCount2); report("baz shiftLeft/Right", failCount3); }
public BDD varRange(BigInteger lo, BigInteger hi) { if (lo.signum() < 0 || hi.compareTo(size()) >= 0 || lo.compareTo(hi) > 0) { throw new BDDException("range <" + lo + ", " + hi + "> is invalid"); } BDDFactory factory = getFactory(); BDD result = factory.zero(); int[] ivar = this.vars(); while (lo.compareTo(hi) <= 0) { BDD v = factory.universe(); for (int n = ivar.length - 1; ; n--) { if (lo.testBit(n)) { v.andWith(factory.ithVar(ivar[n])); } else { v.andWith(factory.nithVar(ivar[n])); } BigInteger mask = BigInteger.ONE.shiftLeft(n).subtract(BigInteger.ONE); if (!lo.testBit(n) && lo.or(mask).compareTo(hi) <= 0) { lo = lo.or(mask).add(BigInteger.ONE); break; } } result.orWith(v); } return result; }
/** *************************************************************************** */ public Fraction(String strFrac) // constructor /** *************************************************************************** */ { int tokens = 0; String strTokens[] = new String[2]; StringTokenizer tokenizer = new StringTokenizer(strFrac, "/"); try { while (tokenizer.hasMoreTokens()) { strTokens[tokens] = tokenizer.nextToken(); tokens++; } } catch (ArrayIndexOutOfBoundsException e) { throw new NumberFormatException(strFrac + " is not a valid fraction."); } if (tokens == 1) { strTokens[1] = new String("1"); } num = new BigInteger(strTokens[0]); denom = new BigInteger(strTokens[1]); if (denom.equals(BigInteger.ZERO)) throw new ArithmeticException( "Denominator in fraction cannot be zero: " + num.toString() + "/" + denom.toString()); if (denom.signum() == -1) { num = num.negate(); denom = denom.negate(); } }
/** * Private constructor, used when you can be certain that the fraction is already in lowest terms. * No check is done to reduce numerator/denominator. A check is still done to maintain a positive * denominator. * * @param isReduced Indicates whether or not the fraction is already known to be reduced to lowest * terms. */ private BigFraction(BigInteger numerator, BigInteger denominator, final Reduced reduced) { if (numerator == null) { throw new IllegalArgumentException("Numerator is null"); } if (denominator == null) { throw new IllegalArgumentException("Denominator is null"); } if (denominator.equals(BigInteger.ZERO)) { throw new ArithmeticException("Divide by zero: fraction denominator is zero."); } // only numerator should be negative. if (denominator.signum() < 0) { numerator = numerator.negate(); denominator = denominator.negate(); } if (reduced == Reduced.NO) { // create a reduced fraction final BigInteger gcd = numerator.gcd(denominator); numerator = numerator.divide(gcd); denominator = denominator.divide(gcd); } this.numerator = numerator; this.denominator = denominator; }
/** * Add the specified value to this reference. * * @param val The value. * @return A reference with an index increased by <code>val</code>. */ public Reference add(BigInteger val) { if (val.signum() == 0) { return this; } else { return new IndexReference(this, val); } }
@TruffleBoundary @Specialization(guards = "isRubyBignum(value)") public byte[] format(int width, int precision, DynamicObject value) { final BigInteger bigInteger = Layouts.BIGNUM.getValue(value); final boolean isNegative = bigInteger.signum() == -1; final boolean negativeAndPadded = isNegative && (this.hasSpaceFlag || this.hasPlusFlag); final String formatted; if (negativeAndPadded) { formatted = bigInteger.abs().toString(2); } else if (!isNegative) { formatted = bigInteger.toString(2); } else { StringBuilder builder = new StringBuilder(); final byte[] bytes = bigInteger.toByteArray(); for (byte b : bytes) { builder.append(Integer.toBinaryString(b & 0xFF)); } formatted = builder.toString(); } return getFormattedString( formatted, width, precision, isNegative, this.hasSpaceFlag, this.hasPlusFlag, this.hasZeroFlag, this.useAlternativeFormat, this.hasMinusFlag, this.format); }
public void objectiveFunctionToLP(ObjectiveFunction obj, StringBuffer buffer) { buffer.append("Minimize \n"); buffer.append("obj: "); IVecInt variables = obj.getVars(); IVec<BigInteger> coeffs = obj.getCoeffs(); int n = variables.size(); if (n > 0) { buffer.append(coeffs.get(0)); buffer.append("x"); buffer.append(variables.get(0)); buffer.append(" "); } BigInteger coeff; for (int i = 1; i < n; i++) { coeff = coeffs.get(i); if (coeff.signum() > 0) { buffer.append("+ " + coeff); } else { buffer.append("- " + coeff.negate()); } buffer.append("x"); buffer.append(variables.get(i)); buffer.append(" "); } }
public void testIsPowerOfTwo() { for (BigInteger x : ALL_BIGINTEGER_CANDIDATES) { // Checks for a single bit set. boolean expected = x.signum() > 0 & x.and(x.subtract(ONE)).equals(ZERO); assertEquals(expected, BigIntegerMath.isPowerOfTwo(x)); } }
/** * Subtract the specified value from this reference. * * @param val The value. * @return A reference with an index decreased by <code>val</code>. */ public Reference subtract(BigInteger val) { if (val.signum() == 0) { return this; } else { return new IndexReference(this, val.negate()); } }
/** * Constructor for PPB. * * @param m The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> represents the reduction * polynomial <code>f(z)</code>. * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> represents the reduction * polynomial <code>f(z)</code>. * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> represents the reduction * polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. */ public F2m(int m, int k1, int k2, int k3, BigInteger x) { // t = m / 32 rounded up to the next integer t = (m + 31) >> 5; this.x = new IntArray(x, t); if ((k2 == 0) && (k3 == 0)) { this.representation = TPB; } else { if (k2 >= k3) { throw new IllegalArgumentException("k2 must be smaller than k3"); } if (k2 <= 0) { throw new IllegalArgumentException("k2 must be larger than 0"); } this.representation = PPB; } if (x.signum() < 0) { throw new IllegalArgumentException("x value cannot be negative"); } this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; }
// c: rand_int private static IRubyObject randInt( ThreadContext context, RandomType random, RubyInteger vmax, boolean restrictive) { if (vmax instanceof RubyFixnum) { long max = RubyNumeric.fix2long(vmax); if (max == 0) { return context.nil; } if (max < 0) { if (restrictive) { return context.nil; } max = -max; } return randLimitedFixnum(context, random, max - 1); } else { BigInteger big = vmax.getBigIntegerValue(); if (big.equals(BigInteger.ZERO)) { return context.nil; } if (big.signum() < 0) { if (restrictive) { return context.nil; } big = big.abs(); } big = big.subtract(BigInteger.ONE); return randLimitedBignum(context, random, RubyBignum.newBignum(context.runtime, big)); } }
public SecT113FieldElement(BigInteger x) { if (x == null || x.signum() < 0 || x.bitLength() > 113) { throw new IllegalArgumentException("x value invalid for SecT113FieldElement"); } this.x = SecT113Field.fromBigInteger(x); }
public IConstr addExactly(IVecInt literals, IVec<BigInteger> coeffs, BigInteger weight) throws ContradictionException { StringBuffer out = getOut(); assert literals.size() == coeffs.size(); this.nbOfConstraints++; int n = literals.size(); if (n > 0) { out.append(coeffs.get(0)); out.append("x"); out.append(literals.get(0)); out.append(" "); } BigInteger coeff; for (int i = 1; i < n; i++) { coeff = coeffs.get(i); if (coeff.signum() > 0) { out.append("+ " + coeff); } else { out.append("- " + coeff.negate()); } out.append("x"); out.append(literals.get(i)); out.append(" "); } out.append("= "); out.append(weight); out.append(" \n"); return FAKE_CONSTR; }
/** * MPI encoded numbers are produced by the OpenSSL BN_bn2mpi function. They consist of a 4 byte * big endian length field, followed by the stated number of bytes representing the number in big * endian format (with a sign bit). * * @param includeLength indicates whether the 4 byte length field should be included */ public static byte[] encodeMPI(BigInteger value, boolean includeLength) { if (value.equals(BigInteger.ZERO)) { if (!includeLength) return new byte[] {}; else return new byte[] {0x00, 0x00, 0x00, 0x00}; } boolean isNegative = value.signum() < 0; if (isNegative) value = value.negate(); byte[] array = value.toByteArray(); int length = array.length; if ((array[0] & 0x80) == 0x80) length++; if (includeLength) { byte[] result = new byte[length + 4]; System.arraycopy(array, 0, result, length - array.length + 3, array.length); uint32ToByteArrayBE(length, result, 0); if (isNegative) result[4] |= 0x80; return result; } else { byte[] result; if (length != array.length) { result = new byte[length]; System.arraycopy(array, 0, result, 1, array.length); } else result = array; if (isNegative) result[0] |= 0x80; return result; } }
protected BigInteger modSubtract(BigInteger x1, BigInteger x2) { BigInteger x3 = x1.subtract(x2); if (x3.signum() < 0) { x3 = x3.add(q); } return x3; }
/** @tests java.math.BigInteger#shiftRight(int) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "shiftRight", args = {int.class}) public void test_shiftRightI() { assertTrue("1 >> 0", BigInteger.valueOf(1).shiftRight(0).equals(BigInteger.ONE)); assertTrue("1 >> 1", BigInteger.valueOf(1).shiftRight(1).equals(BigInteger.ZERO)); assertTrue("1 >> 63", BigInteger.valueOf(1).shiftRight(63).equals(BigInteger.ZERO)); assertTrue("1 >> 64", BigInteger.valueOf(1).shiftRight(64).equals(BigInteger.ZERO)); assertTrue("1 >> 65", BigInteger.valueOf(1).shiftRight(65).equals(BigInteger.ZERO)); assertTrue("1 >> 1000", BigInteger.valueOf(1).shiftRight(1000).equals(BigInteger.ZERO)); assertTrue("-1 >> 0", BigInteger.valueOf(-1).shiftRight(0).equals(minusOne)); assertTrue("-1 >> 1", BigInteger.valueOf(-1).shiftRight(1).equals(minusOne)); assertTrue("-1 >> 63", BigInteger.valueOf(-1).shiftRight(63).equals(minusOne)); assertTrue("-1 >> 64", BigInteger.valueOf(-1).shiftRight(64).equals(minusOne)); assertTrue("-1 >> 65", BigInteger.valueOf(-1).shiftRight(65).equals(minusOne)); assertTrue("-1 >> 1000", BigInteger.valueOf(-1).shiftRight(1000).equals(minusOne)); BigInteger a = BigInteger.ONE; BigInteger c = bi3; BigInteger E = bi3.negate(); BigInteger e = E; for (int i = 0; i < 200; i++) { BigInteger b = BigInteger.ZERO.setBit(i); assertTrue("a==b", a.equals(b)); a = a.shiftLeft(1); assertTrue("a non-neg", a.signum() >= 0); BigInteger d = bi3.shiftRight(i); assertTrue("c==d", c.equals(d)); c = c.shiftRight(1); assertTrue(">>1 == /2", d.divide(two).equals(c)); assertTrue("c non-neg", c.signum() >= 0); BigInteger f = E.shiftRight(i); assertTrue("e==f", e.equals(f)); e = e.shiftRight(1); assertTrue(">>1 == /2", f.subtract(one).divide(two).equals(e)); assertTrue("e negative", e.signum() == -1); assertTrue("b >> i", b.shiftRight(i).equals(one)); assertTrue("b >> i+1", b.shiftRight(i + 1).equals(zero)); assertTrue("b >> i-1", b.shiftRight(i - 1).equals(two)); } }
/** * Determine if this value can be represented as an unsigned long without truncation, that is if * the value is non-negative and its bit pattern completely fits in a long. * * @return true if this value is non-negative and fits in a long false otherwise. */ public boolean isULong() { // Here we have the same problem as for isLong(), plus // the whole range 1<<63 .. (1<<64-1) is allowed. if (bigVal != null) { return bigVal.signum() >= 0 && bigVal.bitLength() <= 64; } return val >= 0; }
/** * Private constructor, used when you can be certain that the fraction is already in lowest terms. * No check is done to reduce numerator/denominator. A check is still done to maintain a positive * denominator. * * @param throwaway unused variable, only here to signal to the compiler that this constructor * should be used. */ private BigFraction(BigInteger numerator, BigInteger denominator, boolean throwaway) { if (denominator.signum() < 0) { this.numerator = numerator.negate(); this.denominator = denominator.negate(); } else { this.numerator = numerator; this.denominator = denominator; } }
Fp(BigInteger q, BigInteger r, BigInteger x) { if (x == null || x.signum() < 0 || x.compareTo(q) >= 0) { throw new IllegalArgumentException("x value invalid in Fp field element"); } this.q = q; this.r = r; this.x = x; }
public static BigInteger toNanoCoins(final String value, final int shift) { final BigInteger nanoCoins = new BigDecimal(value).movePointRight(8 - shift).toBigIntegerExact(); if (nanoCoins.signum() < 0) throw new IllegalArgumentException("negative amount: " + value); if (nanoCoins.compareTo(NetworkParameters.MAX_MONEY) > 0) throw new IllegalArgumentException("amount too large: " + value); return nanoCoins; }
public static Long parseUnsignedLong(String number) { if (number == null) { return null; } BigInteger bigInt = new BigInteger(number.trim()); if (bigInt.signum() < 0 || bigInt.compareTo(two64) != -1) { throw new IllegalArgumentException("overflow: " + number); } return zeroToNull(bigInt.longValue()); }
/** Compute the quadratic character of v, i.e. (v/p) for prime p. */ public int legendre(BigInteger v) { // return v.modPow(p.shiftRight(1), p).add(_1).compareTo(p) == 0 ? -1 : 1; // v^((p-1)/2) mod p // = (v/p) for prime p int J = 1; BigInteger x = v, y = p; if (x.signum() < 0) { x = x.negate(); if (y.testBit(0) && y.testBit(1)) { // y = 3 (mod 4) J = -J; } } while (y.compareTo(_1) > 0) { x = x.mod(y); if (x.compareTo(y.shiftRight(1)) > 0) { x = y.subtract(x); if (y.testBit(0) && y.testBit(1)) { // y = 3 (mod 4) J = -J; } } if (x.signum() == 0) { x = _1; y = _0; J = 0; break; } while (!x.testBit(0) && !x.testBit(1)) { // 4 divides x x = x.shiftRight(2); } if (!x.testBit(0)) { // 2 divides x x = x.shiftRight(1); if (y.testBit(0) && (y.testBit(1) == !y.testBit(2))) { // y = �3 (mod 8) J = -J; } } if (x.testBit(0) && x.testBit(1) && y.testBit(0) && y.testBit(1)) { // x = y = 3 (mod 4) J = -J; } BigInteger t = x; x = y; y = t; // switch x and y } return J; }
public BigInteger getAmount() { BigInteger amount = BigInteger.ZERO; if (hasOutputs()) for (final Output output : outputs) if (output.hasAmount()) amount = amount.add(output.amount); if (amount.signum() != 0) return amount; else return null; }
/** * Compute a cube root of v (mod p) where p = 4 (mod 9). * * @return a cube root of v (mod p) if one exists, or null otherwise. * @exception IllegalArgumentException if the size p of the underlying finite field does not * satisfy p = 4 (mod 9). */ public BigInteger cbrt(BigInteger v) { if (p.mod(_9).intValue() != 4) { throw new IllegalArgumentException( "This implementation is optimized for, and only works with, prime fields GF(p) where p = 4 (mod 9)"); } if (v.signum() == 0) { return _0; } BigInteger r = v.modPow(cbrtExponent, p); // r = v^{(2p + 1)/9} return r.multiply(r).multiply(r).subtract(v).mod(p).signum() == 0 ? r : null; }
public IntArray(BigInteger bigInt, int minIntLen) { if (bigInt.signum() == -1) { throw new IllegalArgumentException("Only positive Integers allowed"); } if (bigInt.equals(ECConstants.ZERO)) { m_ints = new int[] {0}; return; } byte[] barr = bigInt.toByteArray(); int barrLen = barr.length; int barrStart = 0; if (barr[0] == 0) { // First byte is 0 to enforce highest (=sign) bit is zero. // In this case ignore barr[0]. barrLen--; barrStart = 1; } int intLen = (barrLen + 3) / 4; if (intLen < minIntLen) { m_ints = new int[minIntLen]; } else { m_ints = new int[intLen]; } int iarrJ = intLen - 1; int rem = barrLen % 4 + barrStart; int temp = 0; int barrI = barrStart; if (barrStart < rem) { for (; barrI < rem; barrI++) { temp <<= 8; int barrBarrI = barr[barrI]; if (barrBarrI < 0) { barrBarrI += 256; } temp |= barrBarrI; } m_ints[iarrJ--] = temp; } for (; iarrJ >= 0; iarrJ--) { temp = 0; for (int i = 0; i < 4; i++) { temp <<= 8; int barrBarrI = barr[barrI++]; if (barrBarrI < 0) { barrBarrI += 256; } temp |= barrBarrI; } m_ints[iarrJ] = temp; } }