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");
    }
  }
Ejemplo n.º 2
0
  /**
   * Private constructor, used when you can be certain that the fraction is already in lowest terms.
   * No check is done to reduce numerator/denominator. A check is still done to maintain a positive
   * denominator.
   *
   * @param isReduced Indicates whether or not the fraction is already known to be reduced to lowest
   *     terms.
   */
  private BigFraction(BigInteger numerator, BigInteger denominator, final Reduced reduced) {
    if (numerator == null) {
      throw new IllegalArgumentException("Numerator is null");
    }
    if (denominator == null) {
      throw new IllegalArgumentException("Denominator is null");
    }
    if (denominator.equals(BigInteger.ZERO)) {
      throw new ArithmeticException("Divide by zero: fraction denominator is zero.");
    }

    // only numerator should be negative.
    if (denominator.signum() < 0) {
      numerator = numerator.negate();
      denominator = denominator.negate();
    }

    if (reduced == Reduced.NO) {
      // create a reduced fraction
      final BigInteger gcd = numerator.gcd(denominator);
      numerator = numerator.divide(gcd);
      denominator = denominator.divide(gcd);
    }

    this.numerator = numerator;
    this.denominator = denominator;
  }
Ejemplo n.º 3
0
  /**
   * 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;
    }
  }
Ejemplo n.º 4
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;
    }
  }
Ejemplo n.º 5
0
 @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));
 }
Ejemplo n.º 6
0
 @Override
 public int compareTo(BigIntegerFraction o) {
   BigInteger lcm = lcm(denominator, o.denominator);
   return numerator
       .multiply(lcm.divide(denominator))
       .compareTo(o.numerator.multiply(lcm.divide(o.denominator)));
 }
Ejemplo n.º 7
0
  /**
   * 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);
  }
  @Override
  public double getValue(Distribution d, double total, int strategy) {
    BigInteger termA = BigInteger.ONE,
        termB = BigInteger.ZERO,
        termC = BigInteger.ONE,
        termD = BigInteger.ONE;
    double totalReal = 0;

    if (strategy == 0) totalReal = d.total();
    else totalReal = total;

    for (int i = 0; i < d.numClasses(); i++) {
      termA = termA.multiply(factorial(d.perClass(i)));
    }
    System.out.println("TermA = " + termA);
    //	termA = termA.divide(factorial(sum_weights));

    for (int j = 0; j < d.numBags(); j++) {
      termB = factorial(d.perBag(j));
      termC = BigInteger.ONE;
      for (int k = 0; k < d.numClasses(); k++) {
        termC = termC.multiply(factorial(d.perClassPerBag(j, k)));
      }
      termD = termD.multiply(termB.divide(termC));
    }
    System.out.println("TermD = " + termD);
    termA = termA.multiply(termD);
    System.out.println("Fatorial do total = " + factorial(totalReal));
    System.out.println("Final = " + termA.divide(factorial(totalReal)));
    return (termA.divide(factorial(totalReal))).doubleValue();
  }
Ejemplo n.º 9
0
 BigInteger getResult(int n, int r) {
   BigInteger ans;
   ans = F[n];
   ans = ans.divide(F[r]);
   ans = ans.divide(F[n - r]);
   return ans;
 }
Ejemplo n.º 10
0
  /**
   * Constructs a new BigFraction from two BigDecimals.
   *
   * @throws ArithemeticException if denominator == 0.
   */
  private static BigFraction valueOfHelper(
      final BigDecimal numerator, final BigDecimal denominator) {
    // Note: Cannot use .equals(BigDecimal.ZERO), because "0.00" != "0.0".
    if (denominator.unscaledValue().equals(BigInteger.ZERO)) {
      throw new ArithmeticException("Divide by zero: fraction denominator is zero.");
    }

    // Format of BigDecimal: unscaled / 10^scale
    BigInteger tmpNumerator = numerator.unscaledValue();
    BigInteger tmpDenominator = denominator.unscaledValue();

    // (u1/10^s1) / (u2/10^s2) = u1 / (u2 * 10^(s1-s2)) = (u1 * 10^(s2-s1))
    // / u2
    if (numerator.scale() > denominator.scale()) {
      tmpDenominator =
          tmpDenominator.multiply(BigInteger.TEN.pow(numerator.scale() - denominator.scale()));
    } else if (numerator.scale() < denominator.scale()) {
      tmpNumerator =
          tmpNumerator.multiply(BigInteger.TEN.pow(denominator.scale() - numerator.scale()));
      // else: scales are equal, do nothing.
    }

    final BigInteger gcd = tmpNumerator.gcd(tmpDenominator);
    tmpNumerator = tmpNumerator.divide(gcd);
    tmpDenominator = tmpDenominator.divide(gcd);

    if (tmpDenominator.signum() < 0) {
      tmpNumerator = tmpNumerator.negate();
      tmpDenominator = tmpDenominator.negate();
    }

    return new BigFraction(tmpNumerator, tmpDenominator, Reduced.YES);
  }
Ejemplo n.º 11
0
  /** @tests java.math.BigInteger#divide(java.math.BigInteger) */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "divide",
      args = {java.math.BigInteger.class})
  public void test_divideLjava_math_BigInteger() {
    testAllDivs(bi33, bi3);
    testAllDivs(bi22, bi2);
    testAllDivs(bi11, bi1);
    testAllDivs(bi13, bi1);
    testAllDivs(bi13, bi3);
    testAllDivs(bi12, bi1);
    testAllDivs(bi12, bi2);
    testAllDivs(bi23, bi2);
    testAllDivs(bi23, bi3);
    testAllDivs(largePos, bi1);
    testAllDivs(largePos, bi2);
    testAllDivs(largePos, bi3);
    testAllDivs(largeNeg, bi1);
    testAllDivs(largeNeg, bi2);
    testAllDivs(largeNeg, bi3);
    testAllDivs(largeNeg, largePos);
    testAllDivs(largePos, largeNeg);
    testAllDivs(bi3, bi3);
    testAllDivs(bi2, bi2);
    testAllDivs(bi1, bi1);
    testDivRanges(bi1);
    testDivRanges(bi2);
    testDivRanges(bi3);
    testDivRanges(smallPos);
    testDivRanges(largePos);
    testDivRanges(new BigInteger("62EB40FEF85AA9EB", 16));
    testAllDivs(BigInteger.valueOf(0xCC0225953CL), BigInteger.valueOf(0x1B937B765L));

    try {
      largePos.divide(zero);
      fail("ArithmeticException expected");
    } catch (ArithmeticException e) {
    }

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

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

    try {
      zero.divide(zero);
      fail("ArithmeticException expected");
    } catch (ArithmeticException e) {
    }
  }
Ejemplo n.º 12
0
 private void buildDaugiazenklis(
     FormaIrSkaiciai formaIrSkaiciai, BigInteger tukstancioLaipsnis) {
   BigInteger sveikasSkaicius = formaIrSkaiciai.getSveikasisSkaicius();
   Poskyris poskyris = formaIrSkaiciai.getForma().getPoskyris();
   Gimine gimine = formaIrSkaiciai.getForma().getGimine();
   BuilderChecks.checkPowerOfThousand("tukstancioLaipsnis", tukstancioLaipsnis);
   BigInteger sk = sveikasSkaicius;
   BigInteger tukstanciu = sk.divide(tukstancioLaipsnis);
   BigInteger tukstanciuLiekana = sveikasSkaicius.mod(tukstancioLaipsnis);
   if (tukstancioLaipsnis.compareTo(Numbers.THOUSAND) > 0) {
     buildDaugiazenklis(
         formaIrSkaiciai.clone().sveikasSkaicius(tukstanciuLiekana),
         tukstancioLaipsnis.divide(Numbers.THOUSAND));
   } else {
     trizenkliai.buildTrizenklis(formaIrSkaiciai.clone().sveikasSkaicius(tukstanciuLiekana));
   }
   if (tukstanciu.equals(BigInteger.ZERO)) {
     // nieko
   } else if (tukstanciu.equals(BigInteger.ONE)) {
     if (poskyris == Poskyris.Kelintinis && tukstanciuLiekana.equals(BigInteger.ZERO)) {
       zodziai.add(getSuma(Zodis.getKelintinis(tukstancioLaipsnis, gimine, Rusis.Iv)));
     } else {
       zodziai.add(getSuma(Zodis.getPagrindinis(tukstancioLaipsnis, Gimine.V)));
     }
   } else if (tukstanciu.compareTo(BigInteger.ONE) > 0
       && tukstanciu.compareTo(Numbers.THOUSAND) < 0) {
     if (poskyris == Poskyris.Kelintinis && tukstanciuLiekana.equals(BigInteger.ZERO)) {
       zodziai.add(getDaugyba(Zodis.getKelintinis(tukstancioLaipsnis, gimine, Rusis.Iv)));
       trizenkliai.buildTrizenklis(
           formaIrSkaiciai
               .clone()
               .sveikasSkaicius(tukstanciu)
               .poskyris(Poskyris.Pagrindinis)
               .gimine(Gimine.V));
     } else {
       zodziai.add(getDaugyba(Zodis.getPagrindinis(tukstancioLaipsnis, Gimine.V)));
       trizenkliai.buildTrizenklis(
           formaIrSkaiciai
               .clone()
               .sveikasSkaicius(tukstanciu)
               .poskyris(Poskyris.Pagrindinis)
               .gimine(Gimine.V));
     }
   } else {
     if (poskyris == Poskyris.Kelintinis && tukstanciuLiekana.equals(BigInteger.ZERO)) {
       zodziai.add(getDaugyba(Zodis.getKelintinis(tukstancioLaipsnis, gimine, Rusis.Iv)));
       buildDaugiazenklis(
           formaIrSkaiciai.clone().sveikasSkaicius(tukstanciu).poskyris(Poskyris.Pagrindinis),
           tukstancioLaipsnis);
     } else {
       zodziai.add(getDaugyba(Zodis.getPagrindinis(tukstancioLaipsnis, Gimine.V)));
       buildDaugiazenklis(
           formaIrSkaiciai.clone().sveikasSkaicius(tukstanciu).poskyris(Poskyris.Pagrindinis),
           tukstancioLaipsnis);
     }
   }
 }
Ejemplo n.º 13
0
 void simplify() {
     gcd = numerator.gcd(denominator);
     numerator = numerator.divide(gcd);
     denominator = denominator.divide(gcd);
     if (denominator.compareTo(BigInteger.ZERO) < 0) {
         numerator = numerator.negate();
         denominator = denominator.negate();
     }
 }
Ejemplo n.º 14
0
 public static void main(String[] args) {
   BigInteger num = new BigInteger("1050809377681880902769");
   for (BigInteger i = new BigInteger("2");
       num.divide(BigInteger.valueOf(2)).compareTo(i) > 0;
       i = i.add(new BigInteger("1"))) {
     if (num.mod(i).equals(new BigInteger("0"))) {
       System.out.println(i + " * " + num.divide(i));
       break;
     }
   }
 }
Ejemplo n.º 15
0
 private void norm() {
   if (den.compareTo(BigInteger.ZERO) < 0) {
     den = den.negate();
     num = num.negate();
   }
   BigInteger g = num.gcd(den);
   if (g.compareTo(BigInteger.ONE) > 0) {
     num = num.divide(g);
     den = den.divide(g);
   }
 }
Ejemplo n.º 16
0
 private void fix() {
   BigInteger gcd = num.gcd(den);
   if (gcd.compareTo(BigInteger.ONE) > 0) {
     num = num.divide(gcd);
     den = den.divide(gcd);
   }
   if (den.compareTo(BigInteger.ZERO) < 0) {
     num = num.negate();
     den = den.negate();
   }
 }
Ejemplo n.º 17
0
  public static void main(String[] args) {
    Scanner cin = new Scanner(System.in);
    BigInteger n = new BigInteger(cin.next());
    BigInteger m = new BigInteger(cin.next());
    BigInteger a = new BigInteger(cin.next());
    BigInteger x =
        n.mod(a).equals(new BigInteger("0")) ? n.divide(a) : n.divide(a).add(new BigInteger("1"));
    BigInteger y =
        m.mod(a).equals(new BigInteger("0")) ? m.divide(a) : m.divide(a).add(new BigInteger("1"));

    System.out.println(x.multiply(y));
  }
Ejemplo n.º 18
0
 /* reduces Na Da by gcd(Na,Da) */
 private void reduce() {
   if (!zero(num)) {
     if (negative(den)) {
       den = den.negate();
       num = num.negate();
     }
     BigInteger gcd = num.gcd(den);
     if (!one(gcd)) {
       num = num.divide(gcd);
       den = den.divide(gcd);
     }
   } else {
     den = BigInteger.ONE;
   }
 }
Ejemplo n.º 19
0
 /**
  * Computes BigInteger sqrt root of a number (floor value). From: http://stackoverflow
  * .com/questions/4407839/how-can-i-find-the-square-root- of-a-java-biginteger
  *
  * @param x
  * @return
  * @throws IllegalArgumentException
  */
 public static BigInteger bigIntSqRootFloor(BigInteger x) throws IllegalArgumentException {
   if (x.compareTo(BigInteger.ZERO) < 0) {
     throw new IllegalArgumentException("Negative argument.");
   }
   // square roots of 0 and 1 are trivial and
   // y == 0 will cause a divide-by-zero exception
   if (x.equals(BigInteger.ZERO) || x.equals(BigInteger.ONE)) {
     return x;
   } // end if
   BigInteger two = BigInteger.valueOf(2L);
   BigInteger y;
   // starting with y = x / 2 avoids magnitude issues with x squared
   for (y = x.divide(two); y.compareTo(x.divide(y)) > 0; y = ((x.divide(y)).add(y)).divide(two)) ;
   return y;
 } // end bigIntSqRootFloor
Ejemplo n.º 20
0
  private static BigInteger bigIntSqRootFloor(BigInteger x) {
    // square roots of 0 and 1 are trivial and
    // y == 0 will cause a divide-by-zero exception
    if (x == BigInteger.ZERO || x == BigInteger.ONE) {
      return x;
    }

    BigInteger two = BigInteger.valueOf(2);
    BigInteger y;

    // starting with y = x / 2 avoids magnitude issues with x squared
    for (y = x.divide(two); y.compareTo(x.divide(y)) > 0; y = ((x.divide(y)).add(y)).divide(two)) ;

    return y;
  }
Ejemplo n.º 21
0
 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();
   }
 }
    private void checkChunkPoolUray(byte[] chunk, long chunk_start_nonce) {
      Shabal256 md = new Shabal256();
      BigInteger lowest =
          new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
      long lowestscoop = 0;
      for (long i = 0; i < plotFile.getStaggeramt(); i++) {
        md.reset();
        md.update(processing.getGensig());
        md.update(chunk, (int) (i * MiningPlot.SCOOP_SIZE), MiningPlot.SCOOP_SIZE);
        byte[] hash = md.digest();
        BigInteger num =
            new BigInteger(
                1,
                new byte[] {
                  hash[7], hash[6], hash[5], hash[4], hash[3], hash[2], hash[1], hash[0]
                });
        BigInteger deadline = num.divide(BigInteger.valueOf(processing.getBaseTargetL()));

        int compare = deadline.compareTo(lowest);
        if (compare < 0) {
          lowest = deadline;
          lowestscoop = chunk_start_nonce + i;
        }
        if (!running) return;
      }
      registerBestShareForChunk(lowest, lowestscoop, plotFile);
    }
Ejemplo n.º 23
0
  /**
   * Constructs a BigFraction with given numerator and denominator. Fraction will be reduced to
   * lowest terms. If fraction is negative, negative sign will be carried on numerator, regardless
   * of how the values were passed in.
   */
  public BigFraction(BigInteger numerator, BigInteger denominator) {
    if (numerator == null) throw new IllegalArgumentException("Numerator is null");
    if (denominator == null) throw new IllegalArgumentException("Denominator is null");
    if (denominator.equals(BigInteger.ZERO)) throw new ArithmeticException("Divide by zero.");

    // only numerator should be negative.
    if (denominator.signum() < 0) {
      numerator = numerator.negate();
      denominator = denominator.negate();
    }

    // create a reduced fraction
    BigInteger gcd = numerator.gcd(denominator);
    this.numerator = numerator.divide(gcd);
    this.denominator = denominator.divide(gcd);
  }
Ejemplo n.º 24
0
  private static int Phi2(int n, List<Integer> primes) {
    ArrayList<Integer> dividers = new ArrayList<Integer>();
    for (Integer prime : primes) {
      if (n < prime) {
        break;
      }
      if (n % prime == 0) {
        dividers.add(prime);
      }
    }

    BigInteger numerator = BigInteger.valueOf(n);
    BigInteger denominator = BigInteger.ONE;
    for (Integer dividor : dividers) {
      int currentNumerator = dividor - 1;

      numerator = numerator.multiply(BigInteger.valueOf(currentNumerator));
      denominator = denominator.multiply(BigInteger.valueOf(dividor));
    }

    if (numerator.compareTo(denominator) < 0) {
      throw new RuntimeException(numerator + " / " + denominator + ": Bad fraction");
    } else {
      return numerator.divide(denominator).intValue();
    }
  }
Ejemplo n.º 25
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;
    }
Ejemplo n.º 26
0
    BigInteger getAverage() {
      if (BigInteger.ZERO.equals(count)) {
        return BigInteger.ZERO;
      }

      return total.divide(count);
    }
Ejemplo n.º 27
0
 public static BigInteger[] primeFactorsOf(BigInteger pq) {
   BigInteger p = new BigInteger("3");
   while (!pq.mod(p).equals(BigInteger.ZERO)) {
     p = nextPrime(p);
   }
   return new BigInteger[] {p, pq.divide(p)};
 }
Ejemplo n.º 28
0
  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);
    }
  }
Ejemplo n.º 29
0
 public static void main(String[] args) {
   Scanner cin = new Scanner(System.in);
   BigInteger A, B;
   A = cin.nextBigInteger();
   B = cin.nextBigInteger();
   long b = B.longValue();
   if (b == 1) {
     System.out.println(A);
     return;
   }
   long S[] = new long[10010];
   int cnt = 0;
   while (A.compareTo(BigInteger.ZERO) != 0) {
     S[cnt++] = A.mod(B).longValue();
     A = A.divide(B);
   }
   long dp[][] = new long[10010][2];
   dp[0][0] = S[0];
   dp[0][1] = b - S[0];
   for (int i = 1; i < cnt; ++i) {
     dp[i][0] = Math.min(dp[i - 1][0] + S[i], dp[i - 1][1] + S[i] + 1);
     dp[i][1] = Math.min(dp[i - 1][0] + b - S[i], dp[i - 1][1] + b - S[i] - 1);
   }
   long ret = Math.min(dp[cnt - 1][0], dp[cnt - 1][1] + 1);
   System.out.println(ret);
 }
Ejemplo n.º 30
0
 public static void num(String str) {
   BigInteger a = new BigInteger(str);
   StringBuffer sb = new StringBuffer("");
   StringBuffer n = new StringBuffer("");
   while (!(a.divide(div).equals(zero))) {
     sb.insert(0, (char) (a.mod(div).intValue() + 96));
     a = a.divide(div);
   }
   sb.insert(0, (char) (a.intValue() + 96));
   for (int i = 0; i < str.length(); i++) {
     if (i % 3 == 0 && i != 0) n.insert(0, ",");
     n.insert(0, str.charAt(str.length() - i - 1));
   }
   while (sb.length() < 22) sb.append(" ");
   System.out.println(sb + "" + n);
 }