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

The following examples show how to use java.math.BigInteger#divideAndRemainder() . 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 File: Base58Check.java    From blockchain-java with Apache License 2.0 6 votes vote down vote up
/**
 * 转化为 Base58 字符串
 *
 * @param data
 * @return
 */
public static String rawBytesToBase58(byte[] data) {
    // Convert to base-58 string
    StringBuilder sb = new StringBuilder();
    BigInteger num = new BigInteger(1, data);
    while (num.signum() != 0) {
        BigInteger[] quotrem = num.divideAndRemainder(ALPHABET_SIZE);
        sb.append(ALPHABET.charAt(quotrem[1].intValue()));
        num = quotrem[0];
    }

    // Add '1' characters for leading 0-value bytes
    for (int i = 0; i < data.length && data[i] == 0; i++) {
        sb.append(ALPHABET.charAt(0));
    }
    return sb.reverse().toString();
}
 
Example 2
Source File: DivisionOverflow.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    try {
        BigInteger a = BigInteger.ONE.shiftLeft(2147483646);
        BigInteger b = BigInteger.ONE.shiftLeft(1568);
        BigInteger[] qr = a.divideAndRemainder(b);
        BigInteger q = qr[0];
        BigInteger r = qr[1];
        if (!r.equals(BigInteger.ZERO))
            throw new RuntimeException("Incorrect singum() of remainder " + r.signum());
        if (q.bitLength() != 2147482079)
            throw new RuntimeException("Incorrect bitLength() of quotient " + q.bitLength());
        System.out.println("Division of large values passed without overflow.");
    } catch (OutOfMemoryError e) {
        // possible
        System.out.println("OutOfMemoryError");
    }
}
 
Example 3
Source File: DivisionOverflow.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    try {
        BigInteger a = BigInteger.ONE.shiftLeft(2147483646);
        BigInteger b = BigInteger.ONE.shiftLeft(1568);
        BigInteger[] qr = a.divideAndRemainder(b);
        BigInteger q = qr[0];
        BigInteger r = qr[1];
        if (!r.equals(BigInteger.ZERO))
            throw new RuntimeException("Incorrect singum() of remainder " + r.signum());
        if (q.bitLength() != 2147482079)
            throw new RuntimeException("Incorrect bitLength() of quotient " + q.bitLength());
        System.out.println("Division of large values passed without overflow.");
    } catch (OutOfMemoryError e) {
        // possible
        System.out.println("OutOfMemoryError");
    }
}
 
Example 4
Source File: TestFDBigInteger.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static void testQuoRemIteration(FDBigInteger t, FDBigInteger s) throws Exception {
    BigInteger bt = t.toBigInteger();
    BigInteger bs = s.toBigInteger();
    int q = t.quoRemIteration(s);
    BigInteger[] qr = bt.divideAndRemainder(bs);
    if (!BigInteger.valueOf(q).equals(qr[0])) {
        throw new Exception("quoRemIteration returns incorrect quo");
    }
    check(qr[1].multiply(BigInteger.TEN), t, "quoRemIteration returns incorrect rem");
}
 
Example 5
Source File: IPAddressLargeDivision.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
private static String toDefaultString(BigInteger val, BigInteger radix, boolean uppercase, int choppedDigits, int maxDigits) {
	if(val.equals(BigInteger.ZERO)) {
		return "0";
	}
	if(val.equals(BigInteger.ONE)) {
		return "1";
	}
	char dig[] = getDigits(radix.intValue(), uppercase);
	StringBuilder builder;
	if(maxDigits > 0) {//maxDigits is 0 or less if the max digits is unknown
		if(maxDigits <= choppedDigits) {
			return "";
		}
		builder = new StringBuilder();
		toDefaultStringRecursive(val, radix, uppercase, choppedDigits, maxDigits, dig, true, builder);
	} else {
		builder = null;
		do {//value2 == quotient * 16 + remainder
			BigInteger divisorRemainder[] = val.divideAndRemainder(radix);
			BigInteger quotient = divisorRemainder[0];
			BigInteger remainder = divisorRemainder[1];
			if(choppedDigits > 0) {
				--choppedDigits;
				continue;
			}
			if(builder == null) {
				builder = new StringBuilder();
			}
			builder.append(dig[remainder.intValue()]);
			val = quotient;
		} while(!val.equals(BigInteger.ZERO));
		if(builder == null) {
			return "";
		}
		builder.reverse();
	}
	return builder.toString();
}
 
Example 6
Source File: TestFDBigInteger.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testQuoRemIteration(FDBigInteger t, FDBigInteger s) throws Exception {
    BigInteger bt = t.toBigInteger();
    BigInteger bs = s.toBigInteger();
    int q = t.quoRemIteration(s);
    BigInteger[] qr = bt.divideAndRemainder(bs);
    if (!BigInteger.valueOf(q).equals(qr[0])) {
        throw new Exception("quoRemIteration returns incorrect quo");
    }
    check(qr[1].multiply(BigInteger.TEN), t, "quoRemIteration returns incorrect rem");
}
 
Example 7
Source File: BigDecimalEncoding.java    From ndbc with Apache License 2.0 5 votes vote down vote up
private short[] findDigits(final BigInteger i, final short[] current) {
  if (i.signum() != 0) {
    final BigInteger[] array = i.divideAndRemainder(BI_BASE);
    final short[] next = new short[current.length + 1];
    next[0] = (short) array[1].intValue();
    System.arraycopy(current, 0, next, 1, current.length);
    return findDigits(array[0], next);
  } else
    return current;
}
 
Example 8
Source File: BigIntEuclidean.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the EEA on two <code>BigInteger</code>s<br>
 * Implemented from pseudocode on <a href="http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm">Wikipedia</a>.
 *
 * @param a
 * @param b
 * @return a <code>BigIntEuclidean</code> object that contains the result in the variables <code>x</code>, <code>y</code>, and <code>gcd</code>
 */
public static BigIntEuclidean calculate(BigInteger a, BigInteger b)
{
    BigInteger x = BigInteger.ZERO;
    BigInteger lastx = BigInteger.ONE;
    BigInteger y = BigInteger.ONE;
    BigInteger lasty = BigInteger.ZERO;
    while (!b.equals(BigInteger.ZERO))
    {
        BigInteger[] quotientAndRemainder = a.divideAndRemainder(b);
        BigInteger quotient = quotientAndRemainder[0];

        BigInteger temp = a;
        a = b;
        b = quotientAndRemainder[1];

        temp = x;
        x = lastx.subtract(quotient.multiply(x));
        lastx = temp;

        temp = y;
        y = lasty.subtract(quotient.multiply(y));
        lasty = temp;
    }

    BigIntEuclidean result = new BigIntEuclidean();
    result.x = lastx;
    result.y = lasty;
    result.gcd = a;
    return result;
}
 
Example 9
Source File: BigIntegerTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void divideAndRemainder(int order) {
    int failCount1 = 0;

    for (int i=0; i<SIZE; i++) {
        BigInteger x = fetchNumber(order).abs();
        while(x.compareTo(BigInteger.valueOf(3L)) != 1)
            x = fetchNumber(order).abs();
        BigInteger z = x.divide(BigInteger.valueOf(2L));
        BigInteger y[] = x.divideAndRemainder(x);
        if (!y[0].equals(BigInteger.ONE)) {
            failCount1++;
            System.err.println("fail1 x :"+x);
            System.err.println("      y :"+y);
        }
        else if (!y[1].equals(BigInteger.ZERO)) {
            failCount1++;
            System.err.println("fail2 x :"+x);
            System.err.println("      y :"+y);
        }

        y = x.divideAndRemainder(z);
        if (!y[0].equals(BigInteger.valueOf(2))) {
            failCount1++;
            System.err.println("fail3 x :"+x);
            System.err.println("      y :"+y);
        }
    }
    report("divideAndRemainder for " + order + " bits", failCount1);
}
 
Example 10
Source File: ByteUtil.java    From bushido-java-core with GNU General Public License v3.0 5 votes vote down vote up
public static String toBase58(byte[] b) {
    if (b.length == 0)
    {
        return "";
    }

    int lz = 0;
    while (lz < b.length && b[lz] == 0)
    {
        ++lz;
    }
    StringBuffer s = new StringBuffer();
    BigInteger n = new BigInteger(1, b);
    while (n.compareTo(BigInteger.ZERO) > 0)
    {
        BigInteger[] r = n.divideAndRemainder(BigInteger.valueOf(58));
        n = r[0];
        char digit = b58[r[1].intValue()];
        s.append (digit);
    }
    while (lz > 0)
    {
        --lz;
        s.append ("1");
    }
    return s.reverse().toString();
}
 
Example 11
Source File: Duration.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an instance of {@code Duration} from a number of seconds.
 *
 * @param seconds  the number of seconds, up to scale 9, positive or negative
 * @return a {@code Duration}, not null
 * @throws ArithmeticException if numeric overflow occurs
 */
private static Duration create(BigDecimal seconds) {
    BigInteger nanos = seconds.movePointRight(9).toBigIntegerExact();
    BigInteger[] divRem = nanos.divideAndRemainder(BI_NANOS_PER_SECOND);
    if (divRem[0].bitLength() > 63) {
        throw new ArithmeticException("Exceeds capacity of Duration: " + nanos);
    }
    return ofSeconds(divRem[0].longValue(), divRem[1].intValue());
}
 
Example 12
Source File: Duration.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an instance of {@code Duration} from a number of seconds.
 *
 * @param seconds  the number of seconds, up to scale 9, positive or negative
 * @return a {@code Duration}, not null
 * @throws ArithmeticException if numeric overflow occurs
 */
private static Duration create(BigDecimal seconds) {
    BigInteger nanos = seconds.movePointRight(9).toBigIntegerExact();
    BigInteger[] divRem = nanos.divideAndRemainder(BI_NANOS_PER_SECOND);
    if (divRem[0].bitLength() > 63) {
        throw new ArithmeticException("Exceeds capacity of Duration: " + nanos);
    }
    return ofSeconds(divRem[0].longValue(), divRem[1].intValue());
}
 
Example 13
Source File: Duration.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an instance of {@code Duration} from a number of seconds.
 *
 * @param seconds  the number of seconds, up to scale 9, positive or negative
 * @return a {@code Duration}, not null
 * @throws ArithmeticException if numeric overflow occurs
 */
private static Duration create(BigDecimal seconds) {
    BigInteger nanos = seconds.movePointRight(9).toBigIntegerExact();
    BigInteger[] divRem = nanos.divideAndRemainder(BI_NANOS_PER_SECOND);
    if (divRem[0].bitLength() > 63) {
        throw new ArithmeticException("Exceeds capacity of Duration: " + nanos);
    }
    return ofSeconds(divRem[0].longValue(), divRem[1].intValue());
}
 
Example 14
Source File: TestFDBigInteger.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testQuoRemIteration(FDBigInteger t, FDBigInteger s) throws Exception {
    BigInteger bt = t.toBigInteger();
    BigInteger bs = s.toBigInteger();
    int q = t.quoRemIteration(s);
    BigInteger[] qr = bt.divideAndRemainder(bs);
    if (!BigInteger.valueOf(q).equals(qr[0])) {
        throw new Exception("quoRemIteration returns incorrect quo");
    }
    check(qr[1].multiply(BigInteger.TEN), t, "quoRemIteration returns incorrect rem");
}
 
Example 15
Source File: ByteUtils.java    From WalletCordova with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String toBase58 (byte[] b)
{
	if ( b.length == 0 )
	{
		return "";
	}

	int lz = 0;
	while ( lz < b.length && b[lz] == 0 )
	{
		++lz;
	}

	StringBuffer s = new StringBuffer ();
	BigInteger n = new BigInteger (1, b);
	while ( n.compareTo (BigInteger.ZERO) > 0 )
	{
		BigInteger[] r = n.divideAndRemainder (BigInteger.valueOf (58));
		n = r[0];
		char digit = b58[r[1].intValue ()];
		s.append (digit);
	}
	while ( lz > 0 )
	{
		--lz;
		s.append ("1");
	}
	return s.reverse ().toString ();
}
 
Example 16
Source File: BigIntEuclidean.java    From ripple-lib-java with ISC License 5 votes vote down vote up
/**
 * Runs the EEA on two <code>BigInteger</code>s<br>
 * Implemented from pseudocode on <a href="http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm">Wikipedia</a>.
 *
 * @param a
 * @param b
 * @return a <code>BigIntEuclidean</code> object that contains the result in the variables <code>x</code>, <code>y</code>, and <code>gcd</code>
 */
public static BigIntEuclidean calculate(BigInteger a, BigInteger b)
{
    BigInteger x = BigInteger.ZERO;
    BigInteger lastx = BigInteger.ONE;
    BigInteger y = BigInteger.ONE;
    BigInteger lasty = BigInteger.ZERO;
    while (!b.equals(BigInteger.ZERO))
    {
        BigInteger[] quotientAndRemainder = a.divideAndRemainder(b);
        BigInteger quotient = quotientAndRemainder[0];

        BigInteger temp = a;
        a = b;
        b = quotientAndRemainder[1];

        temp = x;
        x = lastx.subtract(quotient.multiply(x));
        lastx = temp;

        temp = y;
        y = lasty.subtract(quotient.multiply(y));
        lasty = temp;
    }

    BigIntEuclidean result = new BigIntEuclidean();
    result.x = lastx;
    result.y = lasty;
    result.gcd = a;
    return result;
}
 
Example 17
Source File: TestFDBigInteger.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static void testQuoRemIteration(FDBigInteger t, FDBigInteger s) throws Exception {
    BigInteger bt = t.toBigInteger();
    BigInteger bs = s.toBigInteger();
    int q = t.quoRemIteration(s);
    BigInteger[] qr = bt.divideAndRemainder(bs);
    if (!BigInteger.valueOf(q).equals(qr[0])) {
        throw new Exception("quoRemIteration returns incorrect quo");
    }
    check(qr[1].multiply(BigInteger.TEN), t, "quoRemIteration returns incorrect rem");
}
 
Example 18
Source File: Duration.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance of {@code Duration} from a number of seconds.
 *
 * @param seconds  the number of seconds, up to scale 9, positive or negative
 * @return a {@code Duration}, not null
 * @throws ArithmeticException if numeric overflow occurs
 */
private static Duration create(BigDecimal seconds) {
    BigInteger nanos = seconds.movePointRight(9).toBigIntegerExact();
    BigInteger[] divRem = nanos.divideAndRemainder(BI_NANOS_PER_SECOND);
    if (divRem[0].bitLength() > 63) {
        throw new ArithmeticException("Exceeds capacity of Duration: " + nanos);
    }
    return ofSeconds(divRem[0].longValue(), divRem[1].intValue());
}
 
Example 19
Source File: BigIntegerIntegral.java    From highj with MIT License 4 votes vote down vote up
@Override
default T2<BigInteger, BigInteger> quotRem(BigInteger a, BigInteger b) {
    BigInteger[] dr = a.divideAndRemainder(b);
    return T2.of(dr[0], dr[1]);
}
 
Example 20
Source File: SymmetricRangeTests.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static void testDivideAndRemainder(String msg, BigInteger dividend, BigInteger divisor,
        BigInteger expectedQuotent, BigInteger expectedRemainder) {
    BigInteger[] qr = dividend.divideAndRemainder(divisor);
    check(msg + "[0]", qr[0], expectedQuotent);
    check(msg + "[1]", qr[1], expectedRemainder);
}