Exemple #1
0
  /**
   * 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;
    }
  }
  /**
   * Create a {@link BigFraction} given the numerator and denominator as <code>BigInteger</code>.
   * The {@link BigFraction} is reduced to lowest terms.
   *
   * @param num the numerator, must not be <code>null</code>.
   * @param den the denominator, must not be <code>null</code>.
   * @throws ArithmeticException if the denominator is <code>zero</code>.
   * @throws NullPointerException if the numerator or the denominator is <code>zero</code>.
   */
  public BigFraction(BigInteger num, BigInteger den) {
    if (num == null) {
      throw MathRuntimeException.createNullPointerException("numerator is null");
    }
    if (den == null) {
      throw MathRuntimeException.createNullPointerException("denominator is null");
    }
    if (BigInteger.ZERO.equals(den)) {
      throw MathRuntimeException.createArithmeticException("denominator must be different from 0");
    }
    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;
    }
  }
 private static String fromDecimalToOtherBase(BigInteger base, BigInteger decimalNumber) {
   String value = BigInteger.ZERO.equals(decimalNumber) ? "0" : "";
   int mod = 0;
   while (!BigInteger.ZERO.equals(decimalNumber)) {
     mod = decimalNumber.mod(base).intValue();
     value = baseDigits.substring(mod, mod + 1) + value;
     decimalNumber = decimalNumber.divide(base);
   }
   return value;
 }
 @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;
 }
  /**
   * Divide the value of this fraction by another, returning the result in reduced form.
   *
   * @param fraction the fraction to divide by, must not be <code>null</code>.
   * @return a {@link BigFraction} instance with the resulting values.
   * @throws NullPointerException if the fraction is <code>null</code>.
   * @throws ArithmeticException if the fraction to divide by is zero.
   */
  public BigFraction divide(final BigFraction fraction) {
    if (BigInteger.ZERO.equals(fraction.numerator)) {
      throw MathRuntimeException.createArithmeticException("denominator must be different from 0");
    }

    return multiply(fraction.reciprocal());
  }
Exemple #6
0
    BigInteger getAverage() {
      if (BigInteger.ZERO.equals(count)) {
        return BigInteger.ZERO;
      }

      return total.divide(count);
    }
Exemple #7
0
  /**
   * Returns a BigDecimal representation of this fraction. If possible, the returned value will be
   * exactly equal to the fraction. If not, the BigDecimal will have a scale large enough to hold
   * the same number of significant figures as both numerator and denominator, or the equivalent of
   * a double-precision number, whichever is more.
   */
  public BigDecimal toBigDecimal() {
    // Implementation note:  A fraction can be represented exactly in base-10 iff its
    // denominator is of the form 2^a * 5^b, where a and b are nonnegative integers.
    // (In other words, if there are no prime factors of the denominator except for
    // 2 and 5, or if the denominator is 1).  So to determine if this denominator is
    // of this form, continually divide by 2 to get the number of 2's, and then
    // continually divide by 5 to get the number of 5's.  Afterward, if the denominator
    // is 1 then there are no other prime factors.

    // Note: number of 2's is given by the number of trailing 0 bits in the number
    int twos = denominator.getLowestSetBit();
    BigInteger tmpDen = denominator.shiftRight(twos); // x / 2^n === x >> n

    final BigInteger FIVE = BigInteger.valueOf(5);
    int fives = 0;
    BigInteger[] divMod = null;

    // while(tmpDen % 5 == 0) { fives++; tmpDen /= 5; }
    while (BigInteger.ZERO.equals((divMod = tmpDen.divideAndRemainder(FIVE))[1])) {
      fives++;
      tmpDen = divMod[0];
    }

    if (BigInteger.ONE.equals(tmpDen)) {
      // This fraction will terminate in base 10, so it can be represented exactly as
      // a BigDecimal.  We would now like to make the fraction of the form
      // unscaled / 10^scale.  We know that 2^x * 5^x = 10^x, and our denominator is
      // in the form 2^twos * 5^fives.  So use max(twos, fives) as the scale, and
      // multiply the numerator and deminator by the appropriate number of 2's or 5's
      // such that the denominator is of the form 2^scale * 5^scale.  (Of course, we
      // only have to actually multiply the numerator, since all we need for the
      // BigDecimal constructor is the scale.
      BigInteger unscaled = numerator;
      int scale = Math.max(twos, fives);

      if (twos < fives) unscaled = unscaled.shiftLeft(fives - twos); // x * 2^n === x << n
      else if (fives < twos) unscaled = unscaled.multiply(FIVE.pow(twos - fives));

      return new BigDecimal(unscaled, scale);
    }

    // else: this number will repeat infinitely in base-10.  So try to figure out
    // a good number of significant digits.  Start with the number of digits required
    // to represent the numerator and denominator in base-10, which is given by
    // bitLength / log[2](10).  (bitLenth is the number of digits in base-2).
    final double LG10 = 3.321928094887362; // Precomputed ln(10)/ln(2), a.k.a. log[2](10)
    int precision = Math.max(numerator.bitLength(), denominator.bitLength());
    precision = (int) Math.ceil(precision / LG10);

    // If the precision is less than 18 digits, use 18 digits so that the number
    // will be at least as accurate as a cast to a double.  For example, with
    // the fraction 1/3, precision will be 1, giving a result of 0.3.  This is
    // quite a bit different from what a user would expect.
    if (precision < 18) precision = 18;

    return toBigDecimal(precision);
  }
  public Element pow(BigInteger n) {
    if (BigInteger.ZERO.equals(n)) {
      setToOne();
      return this;
    }

    elementPowWind(n);

    return this;
  }
Exemple #9
0
  /**
   * Divide the value of this fraction by another, returning the result in reduced form.
   *
   * @param fraction Fraction to divide by, must not be {@code null}.
   * @return a {@link BigFraction} instance with the resulting values.
   * @throws NullArgumentException if the {@code fraction} is {@code null}.
   * @throws ZeroException if the fraction to divide by is zero.
   */
  public BigFraction divide(final BigFraction fraction) {
    if (fraction == null) {
      throw new NullArgumentException(LocalizedFormats.FRACTION);
    }
    if (BigInteger.ZERO.equals(fraction.numerator)) {
      throw new ZeroException(LocalizedFormats.ZERO_DENOMINATOR);
    }

    return multiply(fraction.reciprocal());
  }
 /**
  * Returns the <code>String</code> representing this fraction, ie "num / dem" or just "num" if the
  * denominator is one.
  *
  * @return a string representation of the fraction.
  * @see java.lang.Object#toString()
  */
 @Override
 public String toString() {
   String str = null;
   if (BigInteger.ONE.equals(denominator)) {
     str = numerator.toString();
   } else if (BigInteger.ZERO.equals(numerator)) {
     str = "0";
   } else {
     str = numerator + " / " + denominator;
   }
   return str;
 }
Exemple #11
0
 @RolesAllowed({Role.ADMIN, Role.OPERATOR})
 public void handleEvent(@Observes ClusterKeyEvent event) {
   log.debug("handleEvent: " + event.getClass().getSimpleName());
   if (SecfsEventType.updateKey.equals(event.getType())
       && event.getKey() != null
       && !BigInteger.ZERO.equals(event.getKey())
       && !event.getKey().equals(secret)) {
     secret = event.getKey();
     log.info("handleEvent: updated secret.");
     if (events != null) {
       events.sendEvent(new KeyEvent(SecfsEventType.newKey));
     }
   }
 }
Exemple #12
0
 private void retrieveSecret() {
   if (cache != null) {
     if (secret == null) {
       Object cached = cache.get(SECRET_CACHE_KEY);
       if (cached instanceof BigInteger && !BigInteger.ZERO.equals(cached)) {
         secret = (BigInteger) cached;
         log.info("retrieved secret from cache.");
       }
     }
     if (secret == null) {
       cache.put(SECRET_CACHE_KEY, BigInteger.ZERO);
       log.info("sent NoSecret to cache.");
     }
   }
 }
Exemple #13
0
  /** Constructs a new BigFraction from the given BigDecimal object. */
  private static BigFraction valueOfHelper(final BigDecimal d) {
    // BigDecimal format: unscaled / 10^scale.
    BigInteger tmpNumerator = d.unscaledValue();
    BigInteger tmpDenominator = BigInteger.ONE;

    // Special case for d == 0 (math below won't work right)
    // Note: Cannot use d.equals(BigDecimal.ZERO), because
    // BigDecimal.equals()
    // does not consider numbers equal if they have different scales. So,
    // 0.00 is not equal to BigDecimal.ZERO.
    if (tmpNumerator.equals(BigInteger.ZERO)) {
      return BigFraction.ZERO;
    }

    if (d.scale() < 0) {
      tmpNumerator = tmpNumerator.multiply(BigInteger.TEN.pow(-d.scale()));
    } else if (d.scale() > 0) {
      // Now we have the form: unscaled / 10^scale = unscaled / (2^scale *
      // 5^scale)
      // We know then that gcd(unscaled, 2^scale * 5^scale) = 2^commonTwos
      // * 5^commonFives

      // Easy to determine commonTwos
      final int commonTwos = Math.min(d.scale(), tmpNumerator.getLowestSetBit());
      tmpNumerator = tmpNumerator.shiftRight(commonTwos);
      tmpDenominator = tmpDenominator.shiftLeft(d.scale() - commonTwos);

      // Determining commonFives is a little trickier..
      int commonFives = 0;

      BigInteger[] divMod = null;
      // while(commonFives < d.scale() && tmpNumerator % 5 == 0) {
      // tmpNumerator /= 5; commonFives++; }
      while (commonFives < d.scale()
          && BigInteger.ZERO.equals((divMod = tmpNumerator.divideAndRemainder(BIGINT_FIVE))[1])) {
        tmpNumerator = divMod[0];
        commonFives++;
      }

      if (commonFives < d.scale()) {
        tmpDenominator = tmpDenominator.multiply(BIGINT_FIVE.pow(d.scale() - commonFives));
      }
    }
    // else: d.scale() == 0: do nothing

    // Guaranteed there is no gcd, so fraction is in lowest terms
    return new BigFraction(tmpNumerator, tmpDenominator, Reduced.YES);
  }
 @Override
 public void write(WriteBuffer buff, Object obj) {
   if (!isBigInteger(obj)) {
     super.write(buff, obj);
     return;
   }
   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).putVarLong(x.longValue());
     } else {
       byte[] bytes = x.toByteArray();
       buff.put((byte) TYPE_BIG_INTEGER).putVarInt(bytes.length).put(bytes);
     }
   }
 }
 /**
  * Divide the value of this fraction by the passed <code>BigInteger</code>, ie "this * 1 / bg",
  * returning the result in reduced form.
  *
  * @param bg the <code>BigInteger</code> to divide by, must not be <code>null</code>.
  * @return a {@link BigFraction} instance with the resulting values.
  * @throws NullPointerException if the <code>BigInteger</code> is <code>null</code>.
  * @throws ArithmeticException if the fraction to divide by is zero.
  */
 public BigFraction divide(final BigInteger bg) {
   if (BigInteger.ZERO.equals(bg)) {
     throw MathRuntimeException.createArithmeticException("denominator must be different from 0");
   }
   return new BigFraction(numerator, denominator.multiply(bg));
 }
Exemple #16
0
 /**
  * Divide the value of this fraction by the passed <code>BigInteger</code>, ie "this * 1 / bg",
  * returning the result in reduced form.
  *
  * @param bg the <code>BigInteger</code> to divide by, must not be <code>null</code>.
  * @return a {@link BigFraction} instance with the resulting values.
  * @throws NullArgumentException if the {@code BigInteger} is {@code null}.
  * @throws ZeroException if the fraction to divide by is zero.
  */
 public BigFraction divide(final BigInteger bg) {
   if (BigInteger.ZERO.equals(bg)) {
     throw new ZeroException(LocalizedFormats.ZERO_DENOMINATOR);
   }
   return new BigFraction(numerator, denominator.multiply(bg));
 }
Exemple #17
0
 public boolean isSqr() {
   return BigInteger.ZERO.equals(value) || BigIntegerUtils.legendre(value, field.order) == 1;
 }
Exemple #18
0
 public boolean isZero() {
   return BigInteger.ZERO.equals(value);
 }