public static void main(String args[]) throws Exception { Scanner cin = new Scanner(System.in); BigInteger s, M; int p, i; while (cin.hasNext()) { p = cin.nextInt(); s = BigInteger.valueOf(4); M = BigInteger.ONE; M = M.shiftLeft(p).subtract(BigInteger.ONE); for (i = 0; i < p - 2; ++i) { s = s.multiply(s).subtract(BigInteger.valueOf(2)); while (s.bitLength() > p) { s = s.shiftRight(p).add(s.and(M)); } } if (s.compareTo(BigInteger.ZERO) == 0 || s.compareTo(M) == 0) { System.out.println(0); continue; } String ans = ""; while (s.compareTo(BigInteger.ZERO) > 0) { long buf = s.mod(BigInteger.valueOf(16)).longValue(); ans += Integer.toHexString((int) buf); s = s.divide(BigInteger.valueOf(16)); } for (i = ans.length() - 1; i >= 0; --i) System.out.print(ans.charAt(i)); System.out.println(); } }
/** * Sets the start quantity of the activity based on the data of the shape. * * @param activity * @param shape The resource shape */ private void setStartAndCompletionQuantity(Activity activity, GenericShape shape) { /* Start quantity */ String startQuantity = shape.getProperty("startquantity"); if (startQuantity != null) { try { activity.setStartQuantity(BigInteger.valueOf(Integer.valueOf(startQuantity))); } catch (Exception e) { e.printStackTrace(); /* Set to default value in case of an exception */ activity.setStartQuantity(BigInteger.valueOf(1)); } } /* Completion quantity */ String completionQuantity = shape.getProperty("completionquantity"); if (completionQuantity != null) { try { activity.setCompletionQuantity(BigInteger.valueOf(Integer.valueOf(completionQuantity))); } catch (Exception e) { /* Set to default value in case of an exception */ e.printStackTrace(); activity.setCompletionQuantity(BigInteger.valueOf(1)); } } }
private static void checkNormaliseBaseTenResult(ExpandedDouble orig, NormalisedDecimal result) { String sigDigs = result.getSignificantDecimalDigits(); BigInteger frac = orig.getSignificand(); while (frac.bitLength() + orig.getBinaryExponent() < 200) { frac = frac.multiply(BIG_POW_10); } int binaryExp = orig.getBinaryExponent() - orig.getSignificand().bitLength(); String origDigs = frac.shiftLeft(binaryExp + 1).toString(10); if (!origDigs.startsWith(sigDigs)) { throw new AssertionFailedError("Expected '" + origDigs + "' but got '" + sigDigs + "'."); } double dO = Double.parseDouble("0." + origDigs.substring(sigDigs.length())); double d1 = Double.parseDouble(result.getFractionalPart().toPlainString()); BigInteger subDigsO = BigInteger.valueOf((int) (dO * 32768 + 0.5)); BigInteger subDigsB = BigInteger.valueOf((int) (d1 * 32768 + 0.5)); if (subDigsO.equals(subDigsB)) { return; } BigInteger diff = subDigsB.subtract(subDigsO).abs(); if (diff.intValue() > 100) { // 100/32768 ~= 0.003 throw new AssertionFailedError("minor mistake"); } }
/** Get the data type considering a known max value */ protected final DataTypeDefinition getDataTypeForMAX_VAL( SchemaDefinition schema, BigInteger value) { DataTypeDefinition type; if (BigInteger.valueOf(Byte.MAX_VALUE).compareTo(value) >= 0) { type = new DefaultDataTypeDefinition( this, schema, SQLDataType.NUMERIC.getTypeName(), 0, 2, 0, false, false); } else if (BigInteger.valueOf(Short.MAX_VALUE).compareTo(value) >= 0) { type = new DefaultDataTypeDefinition( this, schema, SQLDataType.NUMERIC.getTypeName(), 0, 4, 0, false, false); } else if (BigInteger.valueOf(Integer.MAX_VALUE).compareTo(value) >= 0) { type = new DefaultDataTypeDefinition( this, schema, SQLDataType.NUMERIC.getTypeName(), 0, 9, 0, false, false); } else if (BigInteger.valueOf(Long.MAX_VALUE).compareTo(value) >= 0) { type = new DefaultDataTypeDefinition( this, schema, SQLDataType.NUMERIC.getTypeName(), 0, 18, 0, false, false); } else { type = new DefaultDataTypeDefinition( this, schema, SQLDataType.NUMERIC.getTypeName(), 0, 38, 0, false, false); } return type; }
/** * Constructs a BigFraction from a floating-point number. * * <p>Warning: round-off error in IEEE floating point numbers can result in answers that are * unexpected. For example, System.out.println(new BigFraction(1.1)) will print: * 2476979795053773/2251799813685248 * * <p>This is because 1.1 cannot be expressed exactly in binary form. The given fraction is * exactly equal to the internal representation of the double-precision floating-point number. * (Which, for 1.1, is: (-1)^0 * 2^0 * (1 + 0x199999999999aL / 0x10000000000000L).) * * <p>NOTE: In many cases, BigFraction(Double.toString(d)) may give a result closer to what the * user expects. */ public BigFraction(double d) { if (Double.isInfinite(d)) throw new IllegalArgumentException("double val is infinite"); if (Double.isNaN(d)) throw new IllegalArgumentException("double val is NaN"); // special case - math below won't work right for 0.0 or -0.0 if (d == 0) { numerator = BigInteger.ZERO; denominator = BigInteger.ONE; return; } final long bits = Double.doubleToLongBits(d); final int sign = (int) (bits >> 63) & 0x1; final int exponent = ((int) (bits >> 52) & 0x7ff) - 0x3ff; final long mantissa = bits & 0xfffffffffffffL; // number is (-1)^sign * 2^(exponent) * 1.mantissa BigInteger tmpNumerator = BigInteger.valueOf(sign == 0 ? 1 : -1); BigInteger tmpDenominator = BigInteger.ONE; // use shortcut: 2^x == 1 << x. if x is negative, shift the denominator if (exponent >= 0) tmpNumerator = tmpNumerator.multiply(BigInteger.ONE.shiftLeft(exponent)); else tmpDenominator = tmpDenominator.multiply(BigInteger.ONE.shiftLeft(-exponent)); // 1.mantissa == 1 + mantissa/2^52 == (2^52 + mantissa)/2^52 tmpDenominator = tmpDenominator.multiply(BigInteger.valueOf(0x10000000000000L)); tmpNumerator = tmpNumerator.multiply(BigInteger.valueOf(0x10000000000000L + mantissa)); BigInteger gcd = tmpNumerator.gcd(tmpDenominator); numerator = tmpNumerator.divide(gcd); denominator = tmpDenominator.divide(gcd); }
public void testFloatToIntegral() throws Exception { // to byte assertEquals(new Byte((byte) 127), convert(new Float(127.127), Byte.class)); assertEquals(new Byte((byte) 127), convert(new Double(127.127), Byte.class)); assertEquals(new Byte((byte) 127), convert(new BigDecimal(127.127), Byte.class)); // to short assertEquals(new Short((short) 127), convert(new Float(127.127), Short.class)); assertEquals(new Short((short) 127), convert(new Double(127.127), Short.class)); assertEquals(new Short((short) 127), convert(new BigDecimal(127.127), Short.class)); // to integer assertEquals(new Integer(127), convert(new Float(127.127), Integer.class)); assertEquals(new Integer(127), convert(new Double(127.127), Integer.class)); assertEquals(new Integer(127), convert(new BigDecimal(127.127), Integer.class)); // to long assertEquals(new Long(127), convert(new Float(127.127), Long.class)); assertEquals(new Long(127), convert(new Double(127.127), Long.class)); assertEquals(new Long(127), convert(new BigDecimal(127.127), Long.class)); // to big integer assertEquals(BigInteger.valueOf(127), convert(new Float(127.127), BigInteger.class)); assertEquals(BigInteger.valueOf(127), convert(new Double(127.127), BigInteger.class)); assertEquals(BigInteger.valueOf(127), convert(new BigDecimal(127.127), BigInteger.class)); }
public static void main(String[] args) throws Exception { BigInteger[] a = new BigInteger[999 + 1]; String[] b = new String[a.length]; long time = System.currentTimeMillis(); a[1] = BigInteger.ZERO; for (int i = 2; i < a.length; i++) { if (i % 2 == 0) a[i] = a[i - 1].multiply(BigInteger.valueOf(2)).add(BigInteger.ONE); else a[i] = a[i - 1].multiply(BigInteger.valueOf(2)).subtract(BigInteger.ONE); } for (int i = 1; i < a.length; i++) { b[i] = a[i].toString(); } System.err.println(System.currentTimeMillis() - time); Scanner sc = new Scanner(System.in); long time1 = System.currentTimeMillis(); // InputReader ir = new InputReader(System.in); while (sc.hasNext()) { // int x = ir.nextInt(); int x = sc.nextInt(); // if (x == -1) // break; System.out.println(b[x]); } System.err.println(System.currentTimeMillis() - time1); }
/** * Convenience method for converting OpenNMS enumerated ticket states to OTRS ticket StateID. * * @param state * @return a BigInteger representing the OTRS StateID. */ private BigInteger openNMSToOTRSState(Ticket.State state) { BigInteger otrsStateId; LOG.debug("getting otrs state from OpenNMS State {}", state.toString()); switch (state) { case OPEN: // ticket is new otrsStateId = BigInteger.valueOf(m_configDao.getOpenStateId()); break; case CANCELLED: // not sure how often we see this otrsStateId = BigInteger.valueOf(m_configDao.getCancelledStateId()); break; case CLOSED: // closed successful otrsStateId = BigInteger.valueOf(m_configDao.getClosedStateId()); break; default: LOG.debug("No valid OpenNMS state on ticket"); otrsStateId = BigInteger.valueOf(m_configDao.getOpenStateId()); } LOG.debug("OpenNMS state was {}", state.toString()); LOG.debug("Setting OTRS state ID to {}", otrsStateId.toString()); return otrsStateId; }
public static void main(String args[]) { Scanner scan = new Scanner(System.in); String numS = scan.next(); BigInteger num = new BigInteger(numS); ///// Numero de numeros. for (int i = 0; i < 100000; i++) { String cadenaj = ""; int a = scan.nextInt(); /////////////// genera la cadena mas larga con X digitos for (int j = 1; j <= a; j++) { cadenaj = cadenaj + "9"; } BigInteger numero2 = new BigInteger(cadenaj); //////////// Genera factorial y compara si es menor long b = 100000; long m = 1; BigInteger factorial = BigInteger.valueOf(m); for (long j = 1; j <= b; j++) { BigInteger x = BigInteger.valueOf(j); factorial = factorial.multiply(x); if ((factorial.compareTo(numero2)) == 1) { System.out.println(j - 1); break; } } } }
/** * A helper class that provides utility methods related to <code>long</code> operations. * * @author Thiago T. Sá * @since 1.0 */ public class LongOperations { /** The {@link Long} minimum value. */ static final BigInteger bigMin = BigInteger.valueOf(Long.MIN_VALUE); /** The {@link Long} maximum value. */ static final BigInteger bigMax = BigInteger.valueOf(Long.MAX_VALUE); /** * Adds two long values. * * @param x the first term. * @param y the second term. * @since 1.0 */ public static long saturatedAdd(long x, long y) { BigInteger sum = BigInteger.valueOf(x).add(BigInteger.valueOf(y)); return bigMin.max(sum).min(bigMax).longValue(); } /** * Multiplies two long values. * * @param x the first factor. * @param y the second factor. * @since 1.0 */ public static long saturatedMultiply(long x, long y) { BigInteger mult = BigInteger.valueOf(x).multiply(BigInteger.valueOf(y)); return bigMin.max(mult).min(bigMax).longValue(); } }
public interface ECConstants { public static final BigInteger ZERO = BigInteger.valueOf(0); public static final BigInteger ONE = BigInteger.valueOf(1); public static final BigInteger TWO = BigInteger.valueOf(2); public static final BigInteger THREE = BigInteger.valueOf(3); public static final BigInteger FOUR = BigInteger.valueOf(4); }
/** Round the rational number up to a whole number. (Mutator) */ public BigInteger roundUp() { if ((this.num.compareTo(new BigInteger("0")) == 0)) { return BigInteger.valueOf(0); } else if (this.isNegative()) { return this.num.divide(this.denom); } else return this.num.divide(this.denom).add(BigInteger.valueOf(1)); } // roundUp()
public static BigInteger twoPower(int num) { if (num == 1) { return BigInteger.valueOf(2); } else { return BigInteger.valueOf(2).multiply(twoPower(num - 1)); } }
public static void testICDE() { // Number of total operations int numberOfTests = 5; // Length of the p, note that n=p.q int lengthp = 512; Paillier esystem = new Paillier(); Random rd = new Random(); PaillierPrivateKey key = KeyGen.PaillierKey(lengthp, 122333356); esystem.setDecryptEncrypt(key); // let's test our algorithm by encrypting and decrypting few instances long start = System.currentTimeMillis(); for (int i = 0; i < numberOfTests; i++) { BigInteger m1 = BigInteger.valueOf(Math.abs(rd.nextLong())); BigInteger m2 = BigInteger.valueOf(Math.abs(rd.nextLong())); BigInteger c1 = esystem.encrypt(m1); BigInteger c2 = esystem.encrypt(m2); BigInteger c3 = esystem.multiply(c1, m2); c1 = esystem.add(c1, c2); c1 = esystem.add(c1, c3); esystem.decrypt(c1); } long stop = System.currentTimeMillis(); System.out.println( "Running time per comparison in milliseconds: " + ((stop - start) / numberOfTests)); }
@Test(timeout = 5000L) public void powExactLongIntExact() { for (long base : LONGS) { for (int power : INTS) { if (power < 0) continue; boolean overflow = BigInteger.valueOf(63 - Long.numberOfLeadingZeros(Math.abs(base))) .multiply(BigInteger.valueOf(power)) .compareTo(BigInteger.valueOf(64)) > 0; BigInteger expected = overflow ? null : BigInteger.valueOf(base).pow(power); if (expected != null && expected.bitLength() <= 63) { long value = powExact(base, power); assertEquals(base + " ^ " + power, expected.longValue(), value); if (value < 10000000000000000L) assertEquals( base + " ^ " + power, power == 1 ? base : (long) Math.pow(base, power), value); assertEquals(base + " ^ " + power, pow(base, power), value); } else { try { powExact(base, power); fail("Should overflow: " + base + " ^ " + power); } catch (ArithmeticException e) { } } } } }
public static char LZExtITChar(long x) { return (char) ((x < 0 ? BigInteger.valueOf(x).add(BigInteger.valueOf(2).shiftLeft(61)) : BigInteger.valueOf(x)) .intValue()); }
@Override public List<RenditionData> getRenditions( CallContext callContext, String repositoryId, String objectId, String renditionFilter, BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) { Lock lock = threadLockService.getReadLock(repositoryId, objectId); try { lock.lock(); List<Rendition> renditions = contentService.getRenditions(repositoryId, objectId); List<RenditionData> results = new ArrayList<RenditionData>(); for (Rendition rnd : renditions) { RenditionDataImpl data = new RenditionDataImpl( rnd.getId(), rnd.getMimetype(), BigInteger.valueOf(rnd.getLength()), rnd.getKind(), rnd.getTitle(), BigInteger.valueOf(rnd.getWidth()), BigInteger.valueOf(rnd.getHeight()), rnd.getRenditionDocumentId()); results.add(data); } return results; } finally { lock.unlock(); } }
public static long[] LURem(long[] x, long[] y) { long[] res = x.clone(); for (int i = 0; i < res.length; ++i) { res[i] = BigInteger.valueOf(res[i]).divide(BigInteger.valueOf(y[i])).longValue(); } return res; }
protected Pair<BigInteger, Boolean> getSizeOf(Object obj) { if (obj == null) return null; if (!(obj instanceof File)) return null; File f = (File) obj; if (f.isFile()) return new BasicPair<BigInteger, Boolean>(BigInteger.valueOf(f.length()), false); if (f.isDirectory()) { boolean hasContinuousChild = ttable.getCachedChildren(obj) == null; BigInteger size = BigInteger.ZERO; for (TreeWalk tw : ttable.walkCachedChildren(obj, TreeWalkType.ByLevel)) { Object n = tw.currentNode(); if (n instanceof ChildrenReader) { hasContinuousChild = true; } else if (n instanceof File) { File nf = (File) n; if (nf.isFile()) { size = size.add(BigInteger.valueOf(nf.length())); } else if (nf.isDirectory()) { if (ttable.getCachedChildren(nf) == null) { hasContinuousChild = true; } } } } return new BasicPair<BigInteger, Boolean>(size, hasContinuousChild); } return null; }
@Test public void shouldNotFindBiggestAndSmallestPrefixWhenDoesNotExist() { Ipv6Range range = Ipv6Range.from("::").to(BigInteger.valueOf(2).pow(128).subtract(BigInteger.valueOf(2))); assertFalse(findMinimumPrefixForPrefixLength(range, 0).isPresent()); assertFalse(findMaximumPrefixForPrefixLength(range, 0).isPresent()); }
@Override public BigInteger convert(Boolean source) { if (source) { return BigInteger.valueOf(101); } return BigInteger.valueOf(1); }
@Test public void testGetVolumeWeightStockPrice() { Transaction localTransactionMockOne = mock(Transaction.class); Transaction localTransactionMockTwo = mock(Transaction.class); Transaction localTransactionMockThree = mock(Transaction.class); DateTime current = DateTime.now(); BigDecimal expectedResult = new BigDecimal(41.96861852).setScale(BIG_DECIMAL_SCALE, ROUNDING_MODE); when(TRANSACTION_MOCK.getTimeStamp()).thenReturn(current.minusMinutes(16)); when(TRANSACTION_MOCK.getQuantity()).thenReturn(BigInteger.valueOf(100)); when(TRANSACTION_MOCK.getPrice()).thenReturn(new BigDecimal(3.123)); when(localTransactionMockOne.getTimeStamp()).thenReturn(current.minusMinutes(1)); when(localTransactionMockOne.getQuantity()).thenReturn(BigInteger.valueOf(50)); when(localTransactionMockOne.getPrice()).thenReturn(new BigDecimal(100.3286)); when(localTransactionMockTwo.getTimeStamp()).thenReturn(current.minusMinutes(5)); when(localTransactionMockTwo.getQuantity()).thenReturn(BigInteger.valueOf(350)); when(localTransactionMockTwo.getPrice()).thenReturn(new BigDecimal(34.231)); when(localTransactionMockThree.getTimeStamp()).thenReturn(current.minusMinutes(10)); when(localTransactionMockThree.getQuantity()).thenReturn(BigInteger.valueOf(5)); when(localTransactionMockThree.getPrice()).thenReturn(new BigDecimal(0.0021)); assertFalse(stockImpl.getVolumeWeightedStockPrice(15).isPresent()); stockImpl.addTransaction(TRANSACTION_MOCK); stockImpl.addTransaction(localTransactionMockOne); stockImpl.addTransaction(localTransactionMockTwo); stockImpl.addTransaction(localTransactionMockThree); assertTrue(stockImpl.getVolumeWeightedStockPrice(15).isPresent()); assertEquals(expectedResult, stockImpl.getVolumeWeightedStockPrice(15).get()); }
@Test public void testDivide() { BigInteger dividend = BigInteger.valueOf(4566746).pow(4); BigInteger divisor = dividend.shiftRight(7).subtract(BigInteger.valueOf(245)); System.out.println( dividend + " / " + divisor + " = " + dividend.divide(divisor) + " rem " + dividend.remainder(divisor)); System.out.println( "N " + dividend.bitLength() + " - D " + divisor.bitLength() + " = " + (dividend.bitLength() - divisor.bitLength())); System.out.println("Q => " + dividend.divide(divisor).bitLength()); System.out.println("R => " + dividend.remainder(divisor).bitLength()); System.out.println("----"); int diff = dividend.bitLength() - divisor.bitLength(); BigInteger n = dividend.shiftRight(divisor.bitLength()); BigInteger d = divisor.shiftRight(divisor.bitLength() - 1); System.out.println(n + " / " + d + " = " + n.divide(d)); }
@Test public void testLaOne() throws InternalTranslationException, InterpreterException { interpreter.setRegister("$v1", BigInteger.ZERO, OperandSize.DWORD, ReilRegisterStatus.DEFINED); interpreter.setRegister( "$v2", BigInteger.valueOf(0x11223344L), OperandSize.DWORD, ReilRegisterStatus.DEFINED); final MockOperandTree operandTree1 = new MockOperandTree(); operandTree1.root = new MockOperandTreeNode(ExpressionType.SIZE_PREFIX, "b4"); operandTree1.root.m_children.add(new MockOperandTreeNode(ExpressionType.REGISTER, "$v1")); final MockOperandTree operandTree2 = new MockOperandTree(); operandTree2.root = new MockOperandTreeNode(ExpressionType.SIZE_PREFIX, "b4"); operandTree2.root.m_children.add(new MockOperandTreeNode(ExpressionType.REGISTER, "$v2")); final List<MockOperandTree> operands = Lists.newArrayList(operandTree1, operandTree2); final IInstruction instruction = new MockInstruction("move", operands); translator.translate(environment, instruction, instructions); interpreter.interpret(TestHelpers.createMapping(instructions), BigInteger.valueOf(0x100)); // check correct outcome assertEquals(3, TestHelpers.filterNativeRegisters(interpreter.getDefinedRegisters()).size()); assertEquals(BigInteger.valueOf(0x11223344L), interpreter.getVariableValue("$v1")); assertEquals(BigInteger.valueOf(0x11223344L), interpreter.getVariableValue("$v2")); assertEquals(BigInteger.ZERO, BigInteger.valueOf(interpreter.getMemorySize())); }
private void getRecords( final int maxRecords, final int startPosition, final int totalResults, final int expectedNext, final int expectedReturn) throws JAXBException, UnsupportedEncodingException { XStream xstream = createXStream(CswConstants.GET_RECORDS_RESPONSE); GetRecordsType query = new GetRecordsType(); query.setMaxRecords(BigInteger.valueOf(maxRecords)); query.setStartPosition(BigInteger.valueOf(startPosition)); CswRecordCollection collection = createCswRecordCollection(query, totalResults); collection.setStartPosition(startPosition); String xml = xstream.toXML(collection); JAXBElement<GetRecordsResponseType> jaxb = (JAXBElement<GetRecordsResponseType>) getJaxBContext() .createUnmarshaller() .unmarshal(new ByteArrayInputStream(xml.getBytes("UTF-8"))); GetRecordsResponseType response = jaxb.getValue(); assertThat( response.getSearchResults().getNumberOfRecordsMatched().intValue(), equalTo(totalResults)); assertThat( response.getSearchResults().getNumberOfRecordsReturned().intValue(), equalTo(expectedReturn)); // assertThat(response.getSearchResults().getAbstractRecord().size(), // equalTo(expectedReturn)); assertThat(response.getSearchResults().getNextRecord().intValue(), equalTo(expectedNext)); }
protected Duration getDuration(DateTimeData date) { int sign = 1; if (date.year < 0 || date.month < 0 || date.day < 0 || date.hour < 0 || date.minute < 0 || date.second < 0) { sign = -1; } return datatypeFactory.newDuration( sign == 1, date.year != DatatypeConstants.FIELD_UNDEFINED ? BigInteger.valueOf(sign * date.year) : null, date.month != DatatypeConstants.FIELD_UNDEFINED ? BigInteger.valueOf(sign * date.month) : null, date.day != DatatypeConstants.FIELD_UNDEFINED ? BigInteger.valueOf(sign * date.day) : null, date.hour != DatatypeConstants.FIELD_UNDEFINED ? BigInteger.valueOf(sign * date.hour) : null, date.minute != DatatypeConstants.FIELD_UNDEFINED ? BigInteger.valueOf(sign * date.minute) : null, date.second != DatatypeConstants.FIELD_UNDEFINED ? new BigDecimal(String.valueOf(sign * date.second)) : null); }
public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { String str = in.readLine(); // Scanner in = new Scanner(System.in); if (str == null) { break; } else { BigInteger num = new BigInteger(str); if (str.equals("0") || str.equals("1")) { System.out.println(str); } else { // BigInteger num = new BigInteger(str); // // System.out.println(num.subtract(BigInteger.ONE).multiply(BigInteger.valueOf(2))); System.out.println(num.multiply(BigInteger.valueOf(2)).subtract(BigInteger.valueOf(2))); } } } }
@Test(timeout = 5000L) public void powExactIntIntExact() { for (int base : INTS) { for (int power : INTS) { if (power < 0) continue; boolean overflow = BigInteger.valueOf(31 - Integer.numberOfLeadingZeros(Math.abs(base))) .multiply(BigInteger.valueOf(power)) .compareTo(BigInteger.valueOf(32)) > 0; BigInteger expected = overflow ? null : BigInteger.valueOf(base).pow(power); if (expected != null && expected.bitLength() <= 31) { int value = powExact(base, power); assertEquals(base + " ^ " + power, expected.intValue(), value); assertEquals(base + " ^ " + power, (int) Math.pow(base, power), value); assertEquals(base + " ^ " + power, pow(base, power), value); } else { try { powExact(base, power); fail("Should overflow: " + base + " ^ " + power); } catch (ArithmeticException e) { } } } } }
static { // TODO: DecimalFormat uses ROUND_HALF_EVEN, not ROUND_HALF_UP // Float: precision of 7 (6 digits after .) floatFormatter = new DecimalFormat(); floatFormatter.applyPattern("0.######E0"); // Double: precision of 16 (15 digits after .) doubleFormatter = new DecimalFormat(); doubleFormatter.applyPattern("0.###############E0"); bigIntTenPow = new BigInteger[20]; bigIntMinUnscaled = new BigInteger[20]; bigIntMaxUnscaled = new BigInteger[20]; for (int i = 0; i < bigIntTenPow.length; i++) { bigIntTenPow[i] = bigIntTen.pow(i); if (i < 19) { bigIntMaxUnscaled[i] = bigIntTenPow[i].subtract(BigInteger.ONE); bigIntMinUnscaled[i] = bigIntMaxUnscaled[i].negate(); } else { bigIntMaxUnscaled[i] = BigInteger.valueOf(Long.MAX_VALUE); bigIntMinUnscaled[i] = BigInteger.valueOf(Long.MIN_VALUE); } } }
private void parsePaymentRequest(Protos.PaymentRequest request) throws PaymentRequestException { try { if (request == null) throw new PaymentRequestException("request cannot be null"); if (!request.hasPaymentDetailsVersion()) throw new PaymentRequestException.InvalidVersion("No version"); if (request.getPaymentDetailsVersion() != 1) throw new PaymentRequestException.InvalidVersion( "Version 1 required. Received version " + request.getPaymentDetailsVersion()); paymentRequest = request; if (!request.hasSerializedPaymentDetails()) throw new PaymentRequestException("No PaymentDetails"); paymentDetails = Protos.PaymentDetails.newBuilder() .mergeFrom(request.getSerializedPaymentDetails()) .build(); if (paymentDetails == null) throw new PaymentRequestException("Invalid PaymentDetails"); if (!paymentDetails.hasNetwork()) params = MainNetParams.get(); else params = NetworkParameters.fromPmtProtocolID(paymentDetails.getNetwork()); if (params == null) throw new PaymentRequestException.InvalidNetwork( "Invalid network " + paymentDetails.getNetwork()); if (paymentDetails.getOutputsCount() < 1) throw new PaymentRequestException.InvalidOutputs("No outputs"); for (Protos.Output output : paymentDetails.getOutputsList()) { if (output.hasAmount()) totalValue = totalValue.add(BigInteger.valueOf(output.getAmount())); } // This won't ever happen in practice. It would only happen if the user provided outputs // that are obviously invalid. Still, we don't want to silently overflow. if (totalValue.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) throw new PaymentRequestException.InvalidOutputs("The outputs are way too big."); } catch (InvalidProtocolBufferException e) { throw new PaymentRequestException(e); } }