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

The following examples show how to use java.math.BigInteger#divideAndRemainder() . 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
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 2
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 Project: blockchain-java   File: Base58Check.java    License: 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 4
Source Project: jdk8u-jdk   File: Duration.java    License: 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 5
Source Project: Java8CN   File: Duration.java    License: 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 6
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 Project: ripple-lib-java   File: BigIntEuclidean.java    License: 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 8
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 9
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 10
Source Project: jdk8u_jdk   File: Duration.java    License: 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 11
/**
 * 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
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 13
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 14
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 15
Source Project: RipplePower   File: BigIntEuclidean.java    License: 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 16
Source Project: ndbc   File: BigDecimalEncoding.java    License: 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 17
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
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 19
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);
}
 
Example 20
Source Project: highj   File: BigIntegerIntegral.java    License: 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]);
}