public static void main(String[] args) {
    int N, F, counter = 0;
    BigInteger current, sum;
    Scanner in = new Scanner(System.in);

    while (true) {
      N = in.nextInt();
      F = in.nextInt();

      if (N == 0 && F == 0) break;
      sum = BigInteger.ZERO;

      for (int i = 0; i < N; i++) {
        current = in.nextBigInteger();
        sum = sum.add(current);
      }

      System.out.println(
          "Bill #"
              + ++counter
              + " costs "
              + sum
              + ": each friend should pay "
              + sum.divide(BigInteger.valueOf(F))
              + "\n");
    }
  }
 private BigInteger factorial(int base) {
   BigInteger value = BigInteger.ONE;
   for (int i = 1; i <= base; i++) {
     value = value.multiply(BigInteger.valueOf(base));
   }
   return value;
 }
Exemplo n.º 3
1
 public static BigInteger combinations(BigInteger n, BigInteger k) {
   if (k.compareTo(n) > 0) {
     return BigInteger.ZERO;
   } else {
     return factorial(n).divide(factorial(k)).divide(factorial(n.subtract(k)));
   }
 }
Exemplo n.º 4
1
  public PublishedShares generalPublishShares(byte[] data, BigInteger[] publicKeys, int choice)
      throws InvalidVSSScheme {

    BigInteger secret = generateSecret();

    // System.out.println("Time = "+(System.currentTimeMillis()-l));
    BigInteger encryptedSecret =
        getPublicInfo().getGeneratorG().modPow(secret, getPublicInfo().getGroupPrimeOrder());

    // System.out.println("Encrypted secret: " + encryptedSecret);
    ByteArrayOutputStream baos = new ByteArrayOutputStream(24);
    byte[] ensecret = encryptedSecret.toByteArray();
    byte[] pad = new byte[24];
    int len = encryptedSecret.toByteArray().length;

    // System.out.println("Orig byte length of encrypted secret: " + len);
    for (int i = 0; i < len; i++) {
      pad[i] = encryptedSecret.toByteArray()[i];
    }

    for (int i = len; i < 24; i++) {
      pad[i] = 0;
    }

    // System.out.println("Converting ensecret.len =" + ensecret.length);
    baos.write(pad, 0, 24);
    // System.out.println("Converted ensecret to byte array with len =" + baos.size());

    byte[] U = encrypt(getPublicInfo(), pad, data);
    return publishShares(secret, U, publicKeys, choice);
  }
Exemplo n.º 5
0
  private static BigInteger getNearby(BigInteger significand, int binExp, int offset) {
    int nExtraBits = 1;
    int nDec = (int) Math.round(3.0 + (64 + nExtraBits) * Math.log10(2.0));
    BigInteger newFrac = significand.shiftLeft(nExtraBits).add(BigInteger.valueOf(offset));

    int gg = 64 + nExtraBits - binExp - 1;

    BigDecimal bd = new BigDecimal(newFrac);
    if (gg > 0) {
      bd = bd.divide(new BigDecimal(BigInteger.ONE.shiftLeft(gg)));
    } else {
      BigInteger frac = newFrac;
      while (frac.bitLength() + binExp < 180) {
        frac = frac.multiply(BigInteger.TEN);
      }
      int binaryExp = binExp - newFrac.bitLength() + frac.bitLength();

      bd = new BigDecimal(frac.shiftRight(frac.bitLength() - binaryExp - 1));
    }
    int excessPrecision = bd.precision() - nDec;
    if (excessPrecision > 0) {
      bd = bd.setScale(bd.scale() - excessPrecision, BigDecimal.ROUND_HALF_UP);
    }
    return bd.unscaledValue();
  }
  /**
   * 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));
      }
    }
  }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!isBigDecimal(obj)) {
     return super.write(buff, obj);
   }
   BigDecimal x = (BigDecimal) obj;
   if (BigDecimal.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_0);
   } else if (BigDecimal.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_1);
   } else {
     int scale = x.scale();
     BigInteger b = x.unscaledValue();
     int bits = b.bitLength();
     if (bits < 64) {
       if (scale == 0) {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL);
       } else {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED);
         DataUtils.writeVarInt(buff, scale);
       }
       DataUtils.writeVarLong(buff, b.longValue());
     } else {
       buff.put((byte) TYPE_BIG_DECIMAL);
       DataUtils.writeVarInt(buff, scale);
       byte[] bytes = b.toByteArray();
       DataUtils.writeVarInt(buff, bytes.length);
       buff = DataUtils.ensureCapacity(buff, bytes.length);
       buff.put(bytes);
     }
   }
   return buff;
 }
Exemplo n.º 8
0
    protected static BigInteger _decodeBigInteger(NSCoder coder, int exponent) {
      short length = coder.decodeShort();
      boolean isNegative = coder.decodeBoolean();
      coder.decodeBoolean();
      int shortCount = coder.decodeInt();
      byte[] bytes = new byte[length * 2];
      int i;
      for (i = 0; i < shortCount; ++i) {
        short part = coder.decodeShort();
        if (i < length) {
          _copyShortToByteArray(part, bytes, (length - (i + 1)) * 2);
        }
      }

      BigInteger result = new BigInteger((isNegative) ? -1 : 1, bytes);

      if (exponent != 0) {
        bytes = new byte[4];
        int powerOfTen = 10;

        for (i = 1; i < exponent; ++i) {
          powerOfTen *= 10;
        }

        _copyIntToByteArray(powerOfTen, bytes, 0);
        BigInteger factor = new BigInteger(bytes);

        result = (exponent > 0) ? result.multiply(factor) : result.divide(factor);
      }

      return result;
    }
Exemplo n.º 9
0
  public static void main(String[] args) {

    Map<Integer, CalcularPolignos> poligono = new HashMap<>();

    Scanner sc = new Scanner(System.in);
    System.out.println("Digite o número de lados do poligono: ");
    BigInteger lados = sc.nextBigInteger();

    int opcao = 0;

    if (lados.intValue() < 3) {
      System.out.println("Valor negativo para número de lados do poligno, tente novamente!");
      main(args);
    } else if (lados.intValue() == 3) {
      opcao = 1;
    } else if (lados.intValue() == 4) {
      opcao = 2;
    } else if (lados.intValue() > 4) {
      opcao = 3;
    }

    System.out.println("Digite o Tamanho do Lado do Poligono: ");
    BigDecimal tamanho = sc.nextBigDecimal();

    poligono.put(1, new Triagulo(lados, tamanho));
    poligono.put(2, new Quadrilatero(lados, tamanho));
    poligono.put(3, new OutrosPoligonos(lados, tamanho));

    Controller cont = new Controller();
    cont.calcular(lados, poligono.get(opcao));
  }
Exemplo n.º 10
0
 public static void odczytPlikuTekstowegoD() throws IOException {
   // dekrypt
   BufferedWriter writer = new BufferedWriter(new FileWriter("odszyfrowanie.txt"));
   FileInputStream fileInput = new FileInputStream("zaszyfrowany.txt");
   FileInputStream filen = new FileInputStream("n.txt");
   FileInputStream filed = new FileInputStream("d.txt");
   String nfile = "";
   String dfile = "";
   int r;
   while ((r = filen.read()) != -1) {
     nfile += (char) r;
   }
   while ((r = filed.read()) != -1) {
     dfile += (char) r;
   }
   filen.close();
   filed.close();
   // System.out.println(dfile);
   // System.out.println(nfile);
   BigInteger n = new BigInteger(nfile);
   BigInteger d = new BigInteger(dfile);
   String content = new String(Files.readAllBytes(Paths.get("zaszyfrowany.txt")));
   String[] odczytane = content.split(" ");
   for (String o : odczytane) {
     BigInteger wynik = new BigInteger(o).modPow(d, n);
     writer.write(new String(wynik.toByteArray()));
   }
   writer.close();
   fileInput.close();
 }
Exemplo n.º 11
0
  public Object evaluate() throws EvaluationException {
    try {
      Number l = (Number) left().evaluate();
      Number r = (Number) right().evaluate();

      if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) {
        String[] parameters = {
          Util.getMessage("EvaluationException.and"),
          left().value().getClass().getName(),
          right().value().getClass().getName()
        };
        throw new EvaluationException(Util.getMessage("EvaluationException.1", parameters));
      } else {
        // Arithmetic and (&)
        // daz        value (new Long (l.longValue () & r.longValue ()));
        BigInteger uL = (BigInteger) coerceToTarget((BigInteger) l);
        BigInteger uR = (BigInteger) coerceToTarget((BigInteger) r);
        value(uL.and(uR));
      }
    } catch (ClassCastException e) {
      String[] parameters = {
        Util.getMessage("EvaluationException.and"),
        left().value().getClass().getName(),
        right().value().getClass().getName()
      };
      throw new EvaluationException(Util.getMessage("EvaluationException.1", parameters));
    }
    return value();
  } // evaluate
Exemplo n.º 12
0
 public Mpk getCertificate(String pseudo, BigInteger APrime, ECPoint h) {
   // Randomly choose primes e and e' like
   Boolean search = true;
   BigInteger ePrime;
   BigInteger e;
   do {
     ePrime = new BigInteger(Constants.KePrime, Constants.certainty, new Random());
     // System.out.println(ePrime);
     e = ePrime.add(Constants.expKe);
     // System.out.println(e);
     if (e.isProbablePrime(Constants.certainty)) {
       search = false;
     }
   } while (search);
   System.out.println("I: e' = " + ePrime);
   // Compute A
   BigInteger A = this.computeA(APrime, e);
   System.out.println("I: A = " + A);
   BigInteger B = this.getRevocationManager().computeB(ePrime);
   Mpk mpk = new Mpk(A, ePrime, B, h);
   this.setNbUsers(this.getNbUsers() + 1);
   this.getMembersList().put(pseudo, mpk);
   System.out.println(
       "I: Protocol OK => Add to list:\n\tIndex = "
           + this.getNbUsers()
           + "\tPseudo = "
           + pseudo
           + "\t(A, e', B, h)");
   return mpk;
 }
  public static synchronized int generateMD5Id(Object... object) {
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos;
      oos = new ObjectOutputStream(baos);

      for (Object x : object) {
        if (x == null) oos.writeChars("null");
        else if (x instanceof Integer) oos.writeInt((Integer) x);
        else if (x instanceof String) oos.writeChars((String) x);
        else if (x instanceof Double) oos.writeDouble((Double) x);
        else if (x instanceof Class) oos.writeChars(((Class<?>) x).getName());
      }

      oos.close();
      MessageDigest m = MessageDigest.getInstance("MD5");
      m.update(baos.toByteArray());
      BigInteger testObjectHash = new BigInteger(m.digest());
      return testObjectHash.intValue();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    return 0;
  }
Exemplo n.º 14
0
 expr negate(PythonTree t, expr o) {
   if (o instanceof Num) {
     Num num = (Num) o;
     if (num.getInternalN() instanceof PyInteger) {
       BigInteger v = ((PyInteger) num.getInternalN()).getValue();
       if (v.compareTo(BigInteger.ZERO) == 1) {
         num.setN(new PyInteger(v.negate()));
         return num;
       }
     } else if (num.getInternalN() instanceof PyFloat) {
       double v = ((PyFloat) num.getInternalN()).getValue();
       if (v >= 0) {
         num.setN(new PyFloat(-v));
         return num;
       }
     } else if (num.getInternalN() instanceof PyComplex) {
       double v = ((PyComplex) num.getInternalN()).imag;
       if (v >= 0) {
         num.setN(new PyComplex(0, -v));
         return num;
       }
     }
   }
   return new UnaryOp(t, unaryopType.USub, o);
 }
Exemplo n.º 15
0
 /** Returns this^exponent. */
 public BigFraction pow(int exponent) {
   if (exponent == 0) return BigFraction.ONE;
   else if (exponent == 1) return this;
   else if (exponent < 0)
     return new BigFraction(denominator.pow(-exponent), numerator.pow(-exponent), true);
   else return new BigFraction(numerator.pow(exponent), denominator.pow(exponent), true);
 }
Exemplo n.º 16
0
 @Test
 public void testUnaryFunctions() {
   for (int i = 0; i < this.iterations; i++) {
     ArbitraryInteger proband = ArbitraryInteger.valueOf(this.randomizer.nextInt());
     assertTrue(proband.signum() * -1 == proband.negate().signum());
     BigInteger t = proband.toNumber();
     assertEquals(t.pow(2), proband.square().toNumber());
     assertTrue(
         proband.isNegativ() && proband.abs().isPositiv()
             || proband.isPositiv() && proband.abs().isPositiv());
     if (!proband.isZero()) {
       ArbitraryRational ratProband = proband.reciprocal();
       if (proband.isPositiv()) {
         assertTrue(ArbitraryInteger.ONE == ratProband.numerator());
         assertTrue(proband == ratProband.denominator());
       } else {
         assertTrue(ArbitraryInteger.MINUS_ONE == ratProband.numerator());
         assertEquals(proband.negate().toNumber(), ratProband.denominator().toNumber());
       }
     }
     assertEquals(proband.toNumber().add(BigInteger.ONE), proband.increment().toNumber());
     assertEquals(proband.toNumber().subtract(BigInteger.ONE), proband.decrement().toNumber());
   }
   try {
     ArbitraryRational ratProband = ArbitraryInteger.ZERO.reciprocal();
     fail("Reciprocal of zero should yield an ArithmeticException");
   } catch (ArithmeticException e) {
     // thats good
   }
   assertTrue(ArbitraryInteger.ONE == ArbitraryInteger.ZERO.increment());
   assertTrue(ArbitraryInteger.TWO == ArbitraryInteger.ONE.increment());
   assertTrue(ArbitraryInteger.MINUS_ONE == ArbitraryInteger.ZERO.decrement());
   assertTrue(ArbitraryInteger.ONE == ArbitraryInteger.TWO.decrement());
 }
  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));
  }
Exemplo n.º 18
0
  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);
  }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!isBigInteger(obj)) {
     return super.write(buff, obj);
   }
   BigInteger x = (BigInteger) obj;
   if (BigInteger.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_0);
   } else if (BigInteger.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_1);
   } else {
     int bits = x.bitLength();
     if (bits <= 63) {
       buff.put((byte) TAG_BIG_INTEGER_SMALL);
       DataUtils.writeVarLong(buff, x.longValue());
     } else {
       buff.put((byte) TYPE_BIG_INTEGER);
       byte[] bytes = x.toByteArray();
       DataUtils.writeVarInt(buff, bytes.length);
       buff = DataUtils.ensureCapacity(buff, bytes.length);
       buff.put(bytes);
     }
   }
   return buff;
 }
Exemplo n.º 20
0
 @Override
 public void write(WriteBuffer buff, Object obj) {
   if (!isBigDecimal(obj)) {
     super.write(buff, obj);
     return;
   }
   BigDecimal x = (BigDecimal) obj;
   if (BigDecimal.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_0);
   } else if (BigDecimal.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_1);
   } else {
     int scale = x.scale();
     BigInteger b = x.unscaledValue();
     int bits = b.bitLength();
     if (bits < 64) {
       if (scale == 0) {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL);
       } else {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED).putVarInt(scale);
       }
       buff.putVarLong(b.longValue());
     } else {
       byte[] bytes = b.toByteArray();
       buff.put((byte) TYPE_BIG_DECIMAL).putVarInt(scale).putVarInt(bytes.length).put(bytes);
     }
   }
 }
Exemplo n.º 21
0
  public static String getFileMD5(File file) {
    if (!file.isFile()) {
      return null;
    }
    MessageDigest digest = null;
    FileInputStream in = null;
    byte buffer[] = new byte[1024];
    int len;
    try {
      digest = MessageDigest.getInstance("MD5");
      in = new FileInputStream(file);
      while ((len = in.read(buffer, 0, 1024)) != -1) {
        digest.update(buffer, 0, len);
      }
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    BigInteger bigInt = new BigInteger(1, digest.digest());

    String md5Value = bigInt.toString(16);
    if (md5Value.length() < 32) {
      for (int i = 0; i < 32 - md5Value.length(); i++) {
        md5Value = "0" + md5Value;
      }
    }
    return md5Value.toLowerCase();
  }
  /**
   * Fetches delta CRLs according to RFC 3280 section 5.2.4.
   *
   * @param currentDate The date for which the delta CRLs must be valid.
   * @param paramsPKIX The extended PKIX parameters.
   * @param completeCRL The complete CRL the delta CRL is for.
   * @return A <code>Set</code> of <code>X509CRL</code>s with delta CRLs.
   * @throws AnnotatedException if an exception occurs while picking the delta CRLs.
   */
  protected static Set getDeltaCRLs(
      Date currentDate, ExtendedPKIXParameters paramsPKIX, X509CRL completeCRL)
      throws AnnotatedException {

    X509CRLStoreSelector deltaSelect = new X509CRLStoreSelector();

    // 5.2.4 (a)
    try {
      deltaSelect.addIssuerName(
          CertPathValidatorUtilities.getIssuerPrincipal(completeCRL).getEncoded());
    } catch (IOException e) {
      throw new AnnotatedException("Cannot extract issuer from CRL.", e);
    }

    BigInteger completeCRLNumber = null;
    try {
      ASN1Primitive derObject =
          CertPathValidatorUtilities.getExtensionValue(completeCRL, CRL_NUMBER);
      if (derObject != null) {
        completeCRLNumber = ASN1Integer.getInstance(derObject).getPositiveValue();
      }
    } catch (Exception e) {
      throw new AnnotatedException("CRL number extension could not be extracted from CRL.", e);
    }

    // 5.2.4 (b)
    byte[] idp = null;
    try {
      idp = completeCRL.getExtensionValue(ISSUING_DISTRIBUTION_POINT);
    } catch (Exception e) {
      throw new AnnotatedException(
          "Issuing distribution point extension value could not be read.", e);
    }

    // 5.2.4 (d)

    deltaSelect.setMinCRLNumber(
        completeCRLNumber == null ? null : completeCRLNumber.add(BigInteger.valueOf(1)));

    deltaSelect.setIssuingDistributionPoint(idp);
    deltaSelect.setIssuingDistributionPointEnabled(true);

    // 5.2.4 (c)
    deltaSelect.setMaxBaseCRLNumber(completeCRLNumber);

    // find delta CRLs
    Set temp = CRL_UTIL.findCRLs(deltaSelect, paramsPKIX, currentDate);

    Set result = new HashSet();

    for (Iterator it = temp.iterator(); it.hasNext(); ) {
      X509CRL crl = (X509CRL) it.next();

      if (isDeltaCRL(crl)) {
        result.add(crl);
      }
    }

    return result;
  }
Exemplo n.º 23
0
  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)));
        }
      }
    }
  }
 private BigInteger previousTransactionId(BigInteger id) {
   if (id.equals(INIT_TXID)) {
     return null;
   } else {
     return id.subtract(BigInteger.ONE);
   }
 }
 private void writeToDatabase(Date time, Value<?> value) {
   try {
     Parameter<?> parameter = value.getParameter();
     if (!parameter.isNumeric()) {
       throw new IllegalArgumentException("The value '" + value.toString() + "' is not numeric!");
     }
     BigDecimal decimalValue = null;
     BigInteger integerValue = null;
     if (Long.class.isAssignableFrom(parameter.getType())) {
       integerValue = BigInteger.valueOf((Long) value.getValue());
     } else {
       decimalValue = BigDecimal.valueOf((Double) value.getValue());
     }
     preparedStatement.setTime(1, new Time(time.getTime()));
     preparedStatement.setString(2, server);
     preparedStatement.setString(3, parameter.getName());
     preparedStatement.setString(4, parameter.getUnit());
     preparedStatement.setString(5, parameter.getType().getName());
     preparedStatement.setString(6, parameter.getDescription());
     preparedStatement.setBigDecimal(7, decimalValue);
     preparedStatement.setLong(8, integerValue.longValue());
     preparedStatement.setString(9, parameter.getLevelOfMeasurement().name());
     preparedStatement.execute();
   } catch (SQLException e) {
     throw new RuntimeException("Could not insert event into event log.", e);
   }
 }
Exemplo n.º 26
0
  /** Returns this - f. */
  public BigFraction subtract(BigFraction f) {
    if (f == null) throw new IllegalArgumentException("Null argument");

    return new BigFraction(
        numerator.multiply(f.denominator).subtract(denominator.multiply(f.numerator)),
        denominator.multiply(f.denominator));
  }
Exemplo n.º 27
0
  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);
      }
    }
  }
Exemplo n.º 28
0
  /** Returns this / b. */
  public BigFraction divide(BigInteger b) {
    if (b == null) throw new IllegalArgumentException("Null argument");

    if (b.equals(BigInteger.ZERO)) throw new ArithmeticException("Divide by zero");

    return new BigFraction(numerator, denominator.multiply(b));
  }
Exemplo n.º 29
0
 // Converts our byte array into a hex string
 private String toHex(byte[] array) {
   BigInteger bigInt = new BigInteger(1, array);
   String hex = bigInt.toString(16);
   int paddingLength = (array.length * 2) - hex.length();
   if (paddingLength > 0) return String.format("%0" + paddingLength + "d", 0) + hex;
   else return hex;
 }
Exemplo n.º 30
0
  /** 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;
  }