/** @tests java.math.BigInteger#divideAndRemainder(java.math.BigInteger) */
  @TestTargetNew(
      level = TestLevel.PARTIAL,
      notes = "ArithmeticException checked",
      method = "divideAndRemainder",
      args = {java.math.BigInteger.class})
  public void test_divideAndRemainderLjava_math_BigInteger() {
    try {
      largePos.divideAndRemainder(zero);
      fail("ArithmeticException expected");
    } catch (ArithmeticException e) {
    }

    try {
      bi1.divideAndRemainder(zero);
      fail("ArithmeticException expected");
    } catch (ArithmeticException e) {
    }

    try {
      bi3.negate().divideAndRemainder(zero);
      fail("ArithmeticException expected");
    } catch (ArithmeticException e) {
    }

    try {
      zero.divideAndRemainder(zero);
      fail("ArithmeticException expected");
    } catch (ArithmeticException e) {
    }
  }
  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);
  }
Exemple #3
0
  public static void main(String[] args) throws NumberFormatException, IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    int t = Integer.parseInt(br.readLine());
    long n;
    BigInteger sum;
    BigInteger[] res;

    for (int i = 0; i < t; i++) {
      br.readLine();
      n = Integer.parseInt(br.readLine());
      if (n == 0) {
        System.out.println("YES");
        continue;
      }
      sum = new BigInteger("0");
      for (int j = 0; j < n; j++) {
        sum = sum.add(new BigInteger(br.readLine()));
      }

      res = sum.divideAndRemainder(new BigInteger(n + ""));
      if (res[1].toString().equals("0")) {
        System.out.println("YES");
      } else {
        System.out.println("NO");
      }
    }
  }
  public static void arithmetic(int order) {
    int failCount = 0;

    for (int i = 0; i < size; i++) {
      BigInteger x = fetchNumber(order);
      while (x.compareTo(BigInteger.ZERO) != 1) x = fetchNumber(order);
      BigInteger y = fetchNumber(order / 2);
      while (x.compareTo(y) == -1) y = fetchNumber(order / 2);
      if (y.equals(BigInteger.ZERO)) y = y.add(BigInteger.ONE);

      BigInteger baz = x.divide(y);
      baz = baz.multiply(y);
      baz = baz.add(x.remainder(y));
      baz = baz.subtract(x);
      if (!baz.equals(BigInteger.ZERO)) failCount++;
    }
    report("Arithmetic I for " + order + " bits", failCount);

    failCount = 0;
    for (int i = 0; i < 100; i++) {
      BigInteger x = fetchNumber(order);
      while (x.compareTo(BigInteger.ZERO) != 1) x = fetchNumber(order);
      BigInteger y = fetchNumber(order / 2);
      while (x.compareTo(y) == -1) y = fetchNumber(order / 2);
      if (y.equals(BigInteger.ZERO)) y = y.add(BigInteger.ONE);

      BigInteger baz[] = x.divideAndRemainder(y);
      baz[0] = baz[0].multiply(y);
      baz[0] = baz[0].add(baz[1]);
      baz[0] = baz[0].subtract(x);
      if (!baz[0].equals(BigInteger.ZERO)) failCount++;
    }
    report("Arithmetic II for " + order + " bits", failCount);
  }
  public static void shift(int order) {
    int failCount1 = 0;
    int failCount2 = 0;
    int failCount3 = 0;

    for (int i = 0; i < 100; i++) {
      BigInteger x = fetchNumber(order);
      int n = Math.abs(rnd.nextInt() % 200);

      if (!x.shiftLeft(n).equals(x.multiply(BigInteger.valueOf(2L).pow(n)))) failCount1++;

      BigInteger y[] = x.divideAndRemainder(BigInteger.valueOf(2L).pow(n));
      BigInteger z = (x.signum() < 0 && y[1].signum() != 0 ? y[0].subtract(BigInteger.ONE) : y[0]);

      BigInteger b = x.shiftRight(n);

      if (!b.equals(z)) {
        System.err.println("Input is " + x.toString(2));
        System.err.println("shift is " + n);

        System.err.println("Divided " + z.toString(2));
        System.err.println("Shifted is " + b.toString(2));
        if (b.toString().equals(z.toString())) System.err.println("Houston, we have a problem.");
        failCount2++;
      }

      if (!x.shiftLeft(n).shiftRight(n).equals(x)) failCount3++;
    }
    report("baz shiftLeft", failCount1);
    report("baz shiftRight", failCount2);
    report("baz shiftLeft/Right", failCount3);
  }
  private void testDiv(BigInteger i1, BigInteger i2) {
    BigInteger q = i1.divide(i2);
    BigInteger r = i1.remainder(i2);
    BigInteger[] temp = i1.divideAndRemainder(i2);

    assertTrue("divide and divideAndRemainder do not agree", q.equals(temp[0]));
    assertTrue("remainder and divideAndRemainder do not agree", r.equals(temp[1]));
    assertTrue(
        "signum and equals(zero) do not agree on quotient", q.signum() != 0 || q.equals(zero));
    assertTrue(
        "signum and equals(zero) do not agree on remainder", r.signum() != 0 || r.equals(zero));
    assertTrue(
        "wrong sign on quotient", q.signum() == 0 || q.signum() == i1.signum() * i2.signum());
    assertTrue("wrong sign on remainder", r.signum() == 0 || r.signum() == i1.signum());
    assertTrue("remainder out of range", r.abs().compareTo(i2.abs()) < 0);
    assertTrue("quotient too small", q.abs().add(one).multiply(i2.abs()).compareTo(i1.abs()) > 0);
    assertTrue("quotient too large", q.abs().multiply(i2.abs()).compareTo(i1.abs()) <= 0);
    BigInteger p = q.multiply(i2);
    BigInteger a = p.add(r);
    assertTrue("(a/b)*b+(a%b) != a", a.equals(i1));
    try {
      BigInteger mod = i1.mod(i2);
      assertTrue("mod is negative", mod.signum() >= 0);
      assertTrue("mod out of range", mod.abs().compareTo(i2.abs()) < 0);
      assertTrue("positive remainder == mod", r.signum() < 0 || r.equals(mod));
      assertTrue(
          "negative remainder == mod - divisor", r.signum() >= 0 || r.equals(mod.subtract(i2)));
    } catch (ArithmeticException e) {
      assertTrue("mod fails on negative divisor only", i2.signum() <= 0);
    }
  }
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);
  }
  static int[] convertToCodewords(BigInteger binary) {
    int[] codewords = new int[10];
    BigInteger[] quotRem;

    quotRem = binary.divideAndRemainder(BigInteger.valueOf(636));
    codewords[9] = quotRem[1].intValue();
    binary = quotRem[0];

    final BigInteger const1365 = BigInteger.valueOf(1365);
    for (int i = 8; i >= 1; i--) {
      quotRem = binary.divideAndRemainder(const1365);
      codewords[i] = quotRem[1].intValue();
      binary = quotRem[0];
    }

    codewords[0] = binary.intValue();

    return codewords;
  }
Exemple #9
0
 public static BigInteger reverse(BigInteger in) {
   BigInteger out = BigInteger.ZERO;
   while (in.compareTo(BigInteger.ZERO) != 0) {
     BigInteger tmp[] = in.divideAndRemainder(BigInteger.TEN);
     out = out.multiply(BigInteger.TEN).add(tmp[1]);
     in = tmp[0];
   }
   //		System.gc();
   return out;
 }
Exemple #10
0
 /**
  * Convert the specified giant value to a string with the specified radix.
  *
  * @param value The value to be converted.
  * @param radix The radix.
  * @return Returns a string representation in the specified radix.
  */
 public static String convert(BigInteger value, int radix) {
   BigInteger bigRadix = BigInteger.valueOf(radix);
   StringBuilder sb = new StringBuilder();
   while (value.compareTo(BigInteger.ZERO) > 0) {
     BigInteger[] result = value.divideAndRemainder(bigRadix);
     sb.append(radixChars[result[1].intValue()]);
     value = result[0];
   }
   sb.reverse();
   return sb.toString();
 }
Exemple #11
0
 @Override
 public void validate(FacesContext context, UIComponent component, Object value)
     throws ValidatorException {
   if (value instanceof String) {
     String enteredOgrn = ((String) value).replaceAll("_+$", "");
     Matcher matcher = OGRN_OGRNIP_REGEX.matcher(enteredOgrn);
     if (!matcher.matches()) {
       FacesMessage message = new FacesMessage();
       message.setDetail(ERROR_MESSAGE);
       message.setSummary(ERROR_MESSAGE);
       message.setSeverity(FacesMessage.SEVERITY_ERROR);
       context.addMessage(component.getClientId(), message);
       throw new ValidatorException(message);
     } else {
       boolean correct = true;
       int length;
       BigInteger divisor;
       if (enteredOgrn.length() == OGRN_LENGTH) {
         length = OGRN_LENGTH;
         divisor = OGRN_DIVISOR;
       } else {
         length = OGRNIP_LENGTH;
         divisor = OGRNIP_DIVISOR;
       }
       int last = Character.getNumericValue(enteredOgrn.charAt(length - 1));
       BigInteger ogrn = new BigInteger(enteredOgrn.substring(0, length - 1));
       BigInteger[] divisionResult = ogrn.divideAndRemainder(divisor);
       int remainder = divisionResult[1].intValue();
       if (remainder > REMAINDER_THRESHOLD) {
         remainder = remainder % 10;
       }
       if (remainder != last) {
         correct = false;
       }
       if (!correct) {
         FacesMessage message = new FacesMessage();
         message.setDetail(INCORRECT_BY_CHECK_DIGIT);
         message.setSummary(INCORRECT_BY_CHECK_DIGIT);
         message.setSeverity(FacesMessage.SEVERITY_ERROR);
         context.addMessage(component.getClientId(), message);
         throw new ValidatorException(message);
       }
     }
   } else {
     FacesMessage message = new FacesMessage();
     message.setDetail(ERROR_MESSAGE);
     message.setSummary(ERROR_MESSAGE);
     message.setSeverity(FacesMessage.SEVERITY_ERROR);
     context.addMessage(component.getClientId(), message);
     throw new ValidatorException(message);
   }
 }
Exemple #12
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);
  }
Exemple #13
0
  /**
   * @param Var varQuotient: destination variable that will receive the quotient of the last divide
   *     operation, recomputed as an integer divide
   * @param Var varRest: destination variable that will receive the rest of the last divide
   *     operation, recomputed as an integer divide
   * @return The last division is done again, as an integer one. This to method must follow
   *     immediatly the division to do.
   */
  public MathDivide to(VarAndEdit varQuotient, VarAndEdit varRest) {
    if (m_dA != null && m_dB != null) {
      // Do the integer division
      BigInteger nA = m_dA.toBigInteger();
      BigInteger nB = m_dB.toBigInteger();
      BigInteger[] t = nA.divideAndRemainder(nB);

      int n = t[0].intValue();
      varQuotient.set(n);

      if (varRest != null) {
        n = t[1].intValue();
        varRest.set(n);
      }
    }
    return this;
  }
Exemple #14
0
  public void EX()
      throws IrregularStringOfBitsException, IntegerOverflowException, TwosComplementSumException,
          DivisionByZeroException {

    // getting values from temporary registers
    BigInteger rs = new BigInteger(TR[RS_FIELD].getHexString(), 16);
    BigInteger rt = new BigInteger(TR[RT_FIELD].getHexString(), 16);

    // performing operations
    BigInteger result[] = null;

    try {
      result = rs.divideAndRemainder(rt);
    } catch (ArithmeticException e) {
      if (cpu.isEnableForwarding()) {
        cpu.getLO().decrWriteSemaphore();
        cpu.getHI().decrWriteSemaphore();
      }

      throw new DivisionByZeroException();
    }

    // writing result in temporary registers
    String tmp = result[0].toString(2); // quotient

    while (tmp.length() < 64) {
      tmp = "0" + tmp;
    }

    TR[LO_REG].setBits(tmp, 0);

    tmp = result[1].toString(2); // reminder

    while (tmp.length() < 64) {
      tmp = "0" + tmp;
    }

    TR[HI_REG].setBits(tmp, 0);

    if (cpu.isEnableForwarding()) {
      doWB();
    }
  }
Exemple #15
0
  /**
   * @param string0 .equals("135")
   * @param string1 .equals("20")
   * @param catchCount ==0
   */
  public static void test(String string0, String string1, int catchCount) {

    try {
      new BigInteger("Togliere sta roba");
    } catch (NumberFormatException ex) {
      catchCount++;
    }

    try {
      new BigInteger((String) null);
    } catch (NullPointerException ex) {
      catchCount++;
    }

    Assertions.checkEquals(2, catchCount);

    BigInteger bigInteger0 = new BigInteger(string0);
    BigInteger bigInteger1 = new BigInteger(string1);

    int int0 = bigInteger0.intValue();
    int int1 = bigInteger1.intValue();

    Assertions.checkEquals(135, int0);
    Assertions.checkEquals(20, int1);

    BigInteger[] bigIntegerArray0 = bigInteger0.divideAndRemainder(bigInteger1);

    BigInteger quotient = bigIntegerArray0[0];
    BigInteger remainder = bigIntegerArray0[1];

    int quotientInteger = quotient.intValue();
    int remainderInteger = remainder.intValue();

    Assertions.checkEquals(6, quotientInteger);
    Assertions.checkEquals(15, remainderInteger);

    BigInteger min = quotient.min(remainder);
    Assertions.checkEquals(min.intValue(), quotient.intValue());
  }
Exemple #16
0
 private void addRemainder(int divisor) {
   BigInteger[] newNum = num.divideAndRemainder(BigInteger.valueOf(divisor));
   nro.add(Integer.valueOf(newNum[1].intValue()));
   num = newNum[0];
 }
Exemple #17
0
 public String divide(String val1, String val2) {
   BigInteger i1 = new BigInteger(val1, 10);
   BigInteger i2 = new BigInteger(val2, 10);
   return i1.divideAndRemainder(i2)[0].toString(10);
 }