Java Code Examples for java.math.BigInteger#divide()
The following examples show how to use
java.math.BigInteger#divide() .
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: astor File: ProperBigFractionFormat.java License: GNU General Public License v2.0 | 6 votes |
/** * 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 2
Source Project: yawl File: CombinationGenerator.java License: GNU Lesser General Public License v3.0 | 6 votes |
public CombinationGenerator (int n, int r) { if (r > n) { throw new IllegalArgumentException (); } if (n < 1) { throw new IllegalArgumentException (); } this.n = n; this.r = r; a = new int[r]; BigInteger nFact = getFactorial (n); BigInteger rFact = getFactorial (r); BigInteger nminusrFact = getFactorial (n - r); total = nFact.divide (rFact.multiply (nminusrFact)); reset (); }
Example 3
Source Project: RipplePower File: ArrayEncoder.java License: Apache License 2.0 | 6 votes |
/** * Converts a byte array produced by {@link #encodeMod3Tight(int[])} back to an <code>int</code> array. * * @param b a byte array * @param N number of coefficients * @return the decoded array */ public static int[] decodeMod3Tight(byte[] b, int N) { BigInteger sum = new BigInteger(1, b); int[] coeffs = new int[N]; for (int i = 0; i < N; i++) { coeffs[i] = sum.mod(BigInteger.valueOf(3)).intValue() - 1; if (coeffs[i] > 1) { coeffs[i] -= 3; } sum = sum.divide(BigInteger.valueOf(3)); } return coeffs; }
Example 4
Source Project: hbase File: RegionSplitter.java License: Apache License 2.0 | 6 votes |
@Override public byte[][] split(int n) { Preconditions.checkArgument(lastRowInt.compareTo(firstRowInt) > 0, "last row (%s) is configured less than first row (%s)", lastRow, firstRow); // +1 to range because the last row is inclusive BigInteger range = lastRowInt.subtract(firstRowInt).add(BigInteger.ONE); Preconditions.checkState(range.compareTo(BigInteger.valueOf(n)) >= 0, "split granularity (%s) is greater than the range (%s)", n, range); BigInteger[] splits = new BigInteger[n - 1]; BigInteger sizeOfEachSplit = range.divide(BigInteger.valueOf(n)); for (int i = 1; i < n; i++) { // NOTE: this means the last region gets all the slop. // This is not a big deal if we're assuming n << MAXHEX splits[i - 1] = firstRowInt.add(sizeOfEachSplit.multiply(BigInteger .valueOf(i))); } return convertToBytes(splits); }
Example 5
Source Project: j2objc File: BigIntegerDivideTest.java License: Apache License 2.0 | 6 votes |
/** * Divide zero by a negative number. */ public void testCase11() { byte aBytes[] = {0}; byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; int aSign = 0; int bSign = -1; byte rBytes[] = {0}; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.divide(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", 0, result.signum()); }
Example 6
Source Project: gemfirexd-oss File: BigIntegerDecimal.java License: Apache License 2.0 | 5 votes |
public long getLong() throws StandardException { if (isNull()) return 0L; BigInteger bi = new BigInteger(data2c); // If at any time we see that the value to be scaled down // is within the range for a long, then we are guaranteed // that the scaled down value is within the range for long. boolean rangeOk = false; if ((bi.compareTo(BigIntegerDecimal.MAXLONG_PLUS_ONE) < 0) && (bi.compareTo(BigIntegerDecimal.MINLONG_MINUS_ONE) > 0)) rangeOk = true; for (int i = 0; i < sqlScale; i++) { bi = bi.divide(BigIntegerDecimal.TEN); if (rangeOk) continue; if ((bi.compareTo(BigIntegerDecimal.MAXLONG_PLUS_ONE) < 0) && (bi.compareTo(BigIntegerDecimal.MINLONG_MINUS_ONE) > 0)) rangeOk = true; } // TODO Range checking if (!rangeOk) throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "BIGINT"); return bi.longValue(); }
Example 7
Source Project: aion File: DiffCalc.java License: MIT License | 5 votes |
public BigInteger calcDifficulty(BlockHeader curBlock, BlockHeader parent) { BigInteger pd = parent.getDifficultyBI(); BigInteger quotient = pd.divide(this.constants.getDifficultyBoundDivisor()); BigInteger sign = getCalcDifficultyMultiplier(curBlock, parent); BigInteger fromParent = pd.add(quotient.multiply(sign)); BigInteger difficulty = max(this.constants.getMinimumMiningDifficulty(), fromParent); return difficulty; }
Example 8
Source Project: aion File: DiffCalc.java License: MIT License | 5 votes |
public BigInteger calcDifficultyAlt( BigInteger currentTimestamp, BigInteger parentTimestamp, BigInteger parentDifficulty) { BigInteger diffBase = parentDifficulty.divide(this.constants.getDifficultyBoundDivisor()); BigInteger diffMultiplier = max( BigInteger.ONE.subtract( currentTimestamp.subtract(parentTimestamp).divide(BigInteger.TEN)), LOWER_BOUND); return parentDifficulty.add(diffBase.multiply(diffMultiplier)); }
Example 9
Source Project: Freerouting File: Point.java License: GNU General Public License v3.0 | 5 votes |
/** * factory method for creating a Point from 3 BigIntegers */ public static Point get_instance(BigInteger p_x, BigInteger p_y, BigInteger p_z) { if (p_z.signum() < 0) { // the dominator z of a RationalPoint is expected to be positive p_x = p_x.negate(); p_y = p_y.negate(); p_z = p_z.negate(); } if ((p_x.mod(p_z)).signum() == 0 && (p_x.mod(p_z)).signum() == 0) { // p_x and p_y can be divided by p_z p_x = p_x.divide(p_z); p_y = p_y.divide(p_z); p_z = BigInteger.ONE; } if (p_z.equals(BigInteger.ONE)) { if ( (p_x.abs()).compareTo(Limits.CRIT_INT_BIG) <= 0 && (p_y.abs()).compareTo(Limits.CRIT_INT_BIG) <= 0 ) { // the Point fits into an IntPoint return new IntPoint(p_x.intValue(), p_y.intValue()); } } return new RationalPoint(p_x, p_y, p_z); }
Example 10
Source Project: UVA File: 12004 Bubble Sort.java License: GNU General Public License v3.0 | 5 votes |
public static void main (String [] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int T=Integer.parseInt(br.readLine()); for (int t=1;t<=T;t++) { //Worse swap count = summation of arithmetic progression = [n(n-1)]/2 //Average swap = worst swap / 2 BigInteger bi=new BigInteger(br.readLine()); BigInteger bi2=bi.subtract(BigInteger.ONE); BigInteger up=bi.multiply(bi2); BigInteger btm=new BigInteger("4"); BigInteger gcd=up.gcd(btm); up=up.divide(gcd); btm=btm.divide(gcd); StringBuilder sb=new StringBuilder(); sb.append("Case "); sb.append(t); sb.append(": "); sb.append(up.toString()); if (!btm.equals(BigInteger.ONE)) { sb.append('/'); sb.append(btm.toString()); } System.out.println(sb.toString()); } }
Example 11
Source Project: TencentKona-8 File: BigIntegerTest.java License: GNU General Public License v2.0 | 5 votes |
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 12
Source Project: coming File: BigFraction_t.java License: MIT License | 5 votes |
/** * Create a {@link BigFraction} given the numerator and denominator as * {@code BigInteger}. The {@link BigFraction} is reduced to lowest terms. * * @param num the numerator, must not be {@code null}. * @param den the denominator, must not be {@code null}. * @throws ZeroException if the denominator is zero. * @throws NullArgumentException if either of the arguments is null */ public BigFraction(BigInteger num, BigInteger den) { MathUtils.checkNotNull(num, LocalizedFormats.NUMERATOR); MathUtils.checkNotNull(den, LocalizedFormats.DENOMINATOR); if (BigInteger.ZERO.equals(den)) { throw new ZeroException(LocalizedFormats.ZERO_DENOMINATOR); } if (BigInteger.ZERO.equals(num)) { numerator = BigInteger.ZERO; denominator = BigInteger.ONE; } else { // reduce numerator and denominator by greatest common denominator final BigInteger gcd = num.gcd(den); if (BigInteger.ONE.compareTo(gcd) < 0) { num = num.divide(gcd); den = den.divide(gcd); } // move sign to numerator if (BigInteger.ZERO.compareTo(den) > 0) { num = num.negate(); den = den.negate(); } // store the values in the final fields numerator = num; denominator = den; } }
Example 13
Source Project: swellrt File: Rational.java License: Apache License 2.0 | 5 votes |
public Rational(BigInteger numerator, BigInteger denominator) { if (denominator.equals(BigInteger.ZERO)) { throw new IllegalArgumentException("Denominator must != 0"); } else if (denominator.compareTo(BigInteger.ZERO) < 0) { denominator = denominator.multiply(BI_M1); numerator = numerator.multiply(BI_M1); } // BigInteger negative = numerator.signum() < 0 ? minusOne : BigInteger.ONE; // numerator = numerator.multiply(negative); BigInteger gcd = numerator.gcd(denominator); this.numerator = numerator.divide(gcd); this.denominator = denominator.divide(gcd); }
Example 14
Source Project: kylin File: Bytes.java License: Apache License 2.0 | 4 votes |
/** * Iterate over keys within the passed range. */ public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive, final int num) { byte[] aPadded; byte[] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be <= 0"); } byte[] prependHeader = { 1, 0 }; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } final BigInteger splitsBI = BigInteger.valueOf(num + 1L); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return i < num + 1; } @Override public byte[] next() { i++; if (i == 0) return a; if (i == num + 1) return b; BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); byte[] padded = curBI.toByteArray(); if (padded[1] == 0) padded = tail(padded, padded.length - 2); else padded = tail(padded, padded.length - 1); return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return () -> iterator; }
Example 15
Source Project: RipplePower File: SimpleBigDecimal.java License: Apache License 2.0 | 4 votes |
public SimpleBigDecimal divide(SimpleBigDecimal b) { checkScale(b); BigInteger dividend = bigInt.shiftLeft(scale); return new SimpleBigDecimal(dividend.divide(b.bigInt), scale); }
Example 16
Source Project: spring-analysis-note File: OpDivide.java License: MIT License | 4 votes |
@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); int scale = Math.max(leftBigDecimal.scale(), rightBigDecimal.scale()); return new TypedValue(leftBigDecimal.divide(rightBigDecimal, scale, RoundingMode.HALF_EVEN)); } 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.divide(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 division return new TypedValue(leftNumber.doubleValue() / rightNumber.doubleValue()); } } return state.operate(Operation.DIVIDE, leftOperand, rightOperand); }
Example 17
Source Project: incubator-tajo File: Bytes.java License: Apache License 2.0 | 4 votes |
/** * Iterate over keys within the passed inclusive range. */ public static Iterable<byte[]> iterateOnSplits( final byte[] a, final byte[]b, final int num) { byte [] aPadded; byte [] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded,bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be < 0"); } byte [] prependHeader = {1, 0}; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); final BigInteger diffBI = stopBI.subtract(startBI); final BigInteger splitsBI = BigInteger.valueOf(num + 1); if(diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch(Exception e) { LOG.error("Exception caught during division", e); return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return i < num+1; } @Override public byte[] next() { i++; if (i == 0) return a; if (i == num + 1) return b; BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); byte [] padded = curBI.toByteArray(); if (padded[1] == 0) padded = tail(padded, padded.length - 2); else padded = tail(padded, padded.length - 1); return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }
Example 18
Source Project: Bytecoder File: CompactNumberFormat.java License: Apache License 2.0 | 4 votes |
private StringBuffer format(BigInteger number, StringBuffer result, FieldDelegate delegate, boolean formatLong) { boolean isNegative = number.signum() == -1; if (isNegative) { number = number.negate(); } int compactDataIndex = selectCompactPattern(number); if (compactDataIndex != -1) { Number divisor = divisors.get(compactDataIndex); int iPart = getIntegerPart(number.doubleValue(), divisor.doubleValue()); String prefix = getAffix(false, true, isNegative, compactDataIndex, iPart); String suffix = getAffix(false, false, isNegative, compactDataIndex, iPart); if (!prefix.isEmpty() || !suffix.isEmpty()) { appendPrefix(result, prefix, delegate); if (number.mod(new BigInteger(divisor.toString())) .compareTo(BigInteger.ZERO) == 0) { number = number.divide(new BigInteger(divisor.toString())); decimalFormat.setDigitList(number, isNegative, 0); decimalFormat.subformatNumber(result, delegate, isNegative, true, getMaximumIntegerDigits(), getMinimumIntegerDigits(), getMaximumFractionDigits(), getMinimumFractionDigits()); } else { // To avoid truncation of fractional part store the value in // BigDecimal and follow BigDecimal path instead of // BigInteger path BigDecimal nDecimal = new BigDecimal(number) .divide(new BigDecimal(divisor.toString()), getRoundingMode()); decimalFormat.setDigitList(nDecimal, isNegative, getMaximumFractionDigits()); decimalFormat.subformatNumber(result, delegate, isNegative, false, getMaximumIntegerDigits(), getMinimumIntegerDigits(), getMaximumFractionDigits(), getMinimumFractionDigits()); } appendSuffix(result, suffix, delegate); } else { number = isNegative ? number.negate() : number; defaultDecimalFormat.format(number, result, delegate, formatLong); } } else { number = isNegative ? number.negate() : number; defaultDecimalFormat.format(number, result, delegate, formatLong); } return result; }
Example 19
Source Project: symja_android_library File: BigRational.java License: GNU General Public License v3.0 | 4 votes |
public BigRational expandTo(BigInteger newDenominator) { BigInteger multiplier = newDenominator.divide(this.den); return new BigRational(this.num.multiply(multiplier), this.den.multiply(multiplier)); }
Example 20
Source Project: beanshell File: Operators.java License: Apache License 2.0 | 4 votes |
static Object bigIntegerBinaryOperation(BigInteger lhs, BigInteger rhs, int kind) { switch(kind) { // arithmetic case PLUS: return lhs.add(rhs); case MINUS: return lhs.subtract(rhs); case STAR: return lhs.multiply(rhs); case SLASH: return lhs.divide(rhs); case MOD: case MODX: return lhs.mod(rhs); case POWER: case POWERX: return lhs.pow(rhs.intValue()); // bitwise case LSHIFT: case LSHIFTX: return lhs.shiftLeft(rhs.intValue()); case RSIGNEDSHIFT: case RSIGNEDSHIFTX: return lhs.shiftRight(rhs.intValue()); case RUNSIGNEDSHIFT: case RUNSIGNEDSHIFTX: if ( lhs.signum() >= 0 ) return lhs.shiftRight(rhs.intValue()); BigInteger opener = BigInteger.ONE.shiftLeft(lhs.toString(2).length() + 1); BigInteger opened = lhs.subtract(opener); BigInteger mask = opener.subtract(BigInteger.ONE).shiftRight(rhs.intValue() + 1); return opened.shiftRight(rhs.intValue()).and(mask); case BIT_AND: case BIT_ANDX: return lhs.and(rhs); case BIT_OR: case BIT_ORX: return lhs.or(rhs); case XOR: case XORX: return lhs.xor(rhs); } throw new InterpreterError( "Unimplemented binary integer operator"); }