Ejemplo n.º 1
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();
   }
 }
Ejemplo n.º 2
0
  public static List range(BigInteger start, BigInteger end) {
    List l = new List();

    long st = start.longValue();
    long en = start.longValue();
    if (BigInteger.valueOf(st).equals(start) && BigInteger.valueOf(en).equals(end)) {
      int dir = st < en ? 1 : -1;
      while (st != en) {
        l.add(BigInteger.valueOf(st));
        st = st + dir;
      }
    } else {
      BigInteger dir;
      if (start.compareTo(end) < 0) {
        dir = BigInteger.ONE;
      } else {
        dir = BigInteger.valueOf(-1);
      }
      while (!start.equals(end)) {
        l.add(start);
        start = start.add(dir);
      }
    }

    return l;
  }
Ejemplo n.º 3
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)));
        }
      }
    }
  }
Ejemplo n.º 4
0
  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));
  }
Ejemplo n.º 5
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);
      }
    }
  }
 public PaillierCryptoSystem(int a, int b) {
   p = a;
   q = b;
   n = BigInteger.valueOf(p).multiply(BigInteger.valueOf(q));
   lambda = psi = lcm(p - 1, q - 1);
   g = n.add(BigInteger.valueOf(1));
   nu = psi.modInverse(n);
 }
 public BigInteger Encrypto(int m, BigInteger n, BigInteger g) {
   int r = new Random().nextInt(10) + 3;
   BigInteger Ans = BigInteger.ZERO;
   BigInteger nSquare = n.multiply(n);
   Ans = g.modPow(BigInteger.valueOf(m), nSquare);
   Ans = Ans.multiply(BigInteger.valueOf(r).modPow(n, nSquare));
   Ans = Ans.remainder(nSquare);
   return Ans;
 }
 public PaillierCryptoSystem() {
   p = 100000 + (new Random().nextInt(4) + 1) * 10000 + 1;
   while (!isPrime(p)) p += 2;
   q = p + 2;
   while (!isPrime(q)) q += 2;
   n = BigInteger.valueOf(p).multiply(BigInteger.valueOf(q));
   lambda = psi = lcm(p - 1, q - 1);
   g = n.add(BigInteger.valueOf(1));
   nu = psi.modInverse(n);
 }
Ejemplo n.º 9
0
 public static void process() {
   Arrays.sort(bookHeight);
   BigInteger sum = BigInteger.valueOf(0L);
   BigInteger temp;
   int iCount = 0;
   for (int i = bookHeight.length - 1; i >= 0; i--) {
     sum = sum.add(BigInteger.valueOf((long) (bookHeight[i])));
     temp = sum.max(b);
     iCount++;
     if (temp.equals(sum)) break;
   }
   System.out.print(iCount);
 }
  public void testReferenceLinkAttribute() {
    Session ssn = SessionManager.getSession();
    DataObject user = ssn.create(getModelName() + ".User");
    user.set("id", BigInteger.valueOf(0));
    user.set("email", "*****@*****.**");
    user.set("firstName", "foo");
    user.set("lastNames", "bar");
    user.save();

    DataObject[] images = new DataObject[2];
    for (int i = 0; i < images.length; i++) {
      images[i] = ssn.create(getModelName() + ".Image");
      images[i].set("id", BigInteger.valueOf(i));
      byte[] bytes = "This is the image.".getBytes();
      images[i].set("bytes", bytes);
      images[i].save();
    }

    // set image
    user.set("image", images[0]);
    user.save();

    // retrieve and then update caption
    DataAssociationCursor dac = ((DataAssociation) images[0].get("users")).cursor();
    dac.next();
    assertNull(dac.getLinkProperty("caption"));
    assertEquals(user, dac.getDataObject());
    DataObject link = dac.getLink();
    link.set("caption", "caption");
    link.save();

    dac = ((DataAssociation) images[0].get("users")).cursor();
    dac.next();
    assertEquals("caption", dac.getLinkProperty("caption"));
    assertEquals(1L, ((DataAssociation) images[0].get("users")).size());

    // set new image as image
    user.set("image", images[1]);
    user.save();

    // check that old image is no longer associated with user
    assertEquals(0L, ((DataAssociation) images[0].get("users")).size());

    // check that new image is associated with user and has no caption
    dac = ((DataAssociation) images[1].get("users")).cursor();
    dac.next();
    assertNull(dac.getLinkProperty("caption"));
    assertEquals(1L, ((DataAssociation) images[1].get("users")).size());
  }
Ejemplo n.º 11
0
  public void testArticleImageLink() {
    Session ssn = SessionManager.getSession();
    DataObject article = ssn.create(getModel() + ".Article");
    article.set("id", BigInteger.ZERO);
    String text = "This is the article text.";
    article.set("text", text);

    for (int i = 0; i < 10; i++) {
      DataObject image = ssn.create(getModel() + ".Image");
      image.set("id", new BigInteger(Integer.toString(i)));
      byte[] bytes = "This is the image.".getBytes();
      image.set("bytes", bytes);
      image.save();
    }

    DataAssociation links = (DataAssociation) article.get("images");
    DataCollection images = ssn.retrieve(getModel() + ".Image");
    while (images.next()) {
      DataObject image = images.getDataObject();
      DataObject link = ssn.create(getModel() + ".ArticleImageLink");
      link.set("article", article);
      link.set("image", image);
      link.set("caption", "The caption for: " + image.getOID());
      links.add(link);
    }

    article.save();

    DataAssociationCursor cursor = links.cursor();
    assertEquals(10, cursor.size());

    DataCollection aiLinks = ssn.retrieve(getModel() + ".ArticleImageLink");
    aiLinks.addEqualsFilter("image.id", new BigDecimal(5));
    if (aiLinks.next()) {
      DataObject linkArticle = (DataObject) aiLinks.get("article");
      DataObject linkImage = (DataObject) aiLinks.get("image");
      String caption = (String) aiLinks.get("caption");
      assertEquals(BigInteger.valueOf(0), linkArticle.get("id"));
      assertEquals(BigInteger.valueOf(5), linkImage.get("id"));

      if (aiLinks.next()) {
        fail("too many rows");
      }
    } else {
      fail("no rows returned");
    }

    article.delete();
  }
Ejemplo n.º 12
0
  public static void main(String[] args) throws Exception {
    BigInteger T = BigInteger.valueOf(0);
    BigInteger TB = BigInteger.valueOf(0);
    BigInteger NTB = BigInteger.valueOf(0);
    BigInteger S = BigInteger.valueOf(0);
    BigInteger MAX = BigInteger.valueOf(1);
    int j;
    for (j = 0; j < 100; j++) MAX = MAX.multiply(BigInteger.valueOf(10));
    for (; ; ) {
      int i, t, a, b;
      if (in.nextToken() != StreamTokenizer.TT_NUMBER) break;
      t = (int) in.nval;
      if (in.nextToken() != StreamTokenizer.TT_NUMBER) break;
      a = (int) in.nval;
      if (in.nextToken() != StreamTokenizer.TT_NUMBER) break;
      b = (int) in.nval;

      // System.out.print("(");
      // System.out.print(t);
      // System.out.print("^");
      // System.out.print(a);
      // System.out.print("-1)/(");
      // System.out.print(t);
      // System.out.print("^");
      // System.out.print(b);
      // System.out.print("-1) ");
      if (t == 1 || a % b != 0) {
        System.out.print("bad!\n");
        continue;
      }

      T = BigInteger.valueOf(t);
      TB = BigInteger.valueOf(1);
      for (i = 0; i < b; i++) {
        TB = TB.multiply(T);
        if (TB.compareTo(MAX) >= 0) break;
      }
      NTB = BigInteger.valueOf(1);
      S = BigInteger.valueOf(0);
      for (i = 0; i < a; i += b) {
        S = S.add(NTB);
        if (S.compareTo(MAX) >= 0) break;
        NTB = NTB.multiply(TB);
      }
      if (S.compareTo(MAX) >= 0) System.out.print("bad!");
      else System.out.print(S);
      System.out.print("\n");
    }
  }
Ejemplo n.º 13
0
  void solve(InputReader in) {

    try {

      long start = System.currentTimeMillis();

      F[0] = BigInteger.ONE;
      for (i = 1; i <= 30; ++i) F[i] = F[i - 1].multiply(BigInteger.valueOf(i));

      for (i = 1; i <= 30; ++i) {
        for (j = 1; j <= i; ++j) {
          C[i][j] = getResult(i, j);
        }
      }

      t = in.nextInt();
      while (t-- > 0) {
        for (i = 1; i <= 30; ++i) g[i] = new ArrayList();
        n = in.nextInt();
        for (i = 1; i <= n; ++i) a[i] = in.nextInt();
        root = a[1];
        p = 2;
        Construct(root, 1, 30);
        Pair ans = Calculate(root);
        System.out.println(ans.x);
      }

      long end = System.currentTimeMillis();
      if (time) System.out.println("Execution time: " + (double) (end - start) / 1000.0);
    } catch (Exception e) {
      System.out.println("Error: " + e);
    }
    ;
  }
Ejemplo n.º 14
0
Archivo: Main.java Proyecto: mrain/acm
 public static boolean check(long n, int p) {
   BigInteger P = BigInteger.TEN.pow(p), Q = BigInteger.TEN.pow(p - 1);
   BigInteger N = BigInteger.ONE, tmp = BigInteger.valueOf(2);
   while (n > 0) {
     if ((n % 2) == 1) {
       N = N.multiply(tmp);
       N = N.mod(P);
     }
     tmp = tmp.multiply(tmp);
     tmp = tmp.mod(P);
     n >>= 1;
   }
   N = N.divide(Q);
   if (N.equals(BigInteger.ONE) || N.equals(BigInteger.valueOf(2))) return true;
   else return false;
 }
Ejemplo n.º 15
0
 /**
  * Coerce a string into a Whiley int list.
  *
  * @param str
  * @return
  */
 public static List str2il(String str) {
   List r = new List(str.length());
   for (int i = 0; i != str.length(); ++i) {
     r.add(BigInteger.valueOf(str.charAt(i)));
   }
   return r;
 }
Ejemplo n.º 16
0
 static long calc(BigInteger k1) {
   long x = 1;
   while (true) {
     long res = mul(k1, x, BigInteger.valueOf(1000000000000l)).longValue();
     if (x == res && res > 100000000000l) return res;
     x = res;
   }
 }
Ejemplo n.º 17
0
 public static int turn(int p, int ix) {
     char c = a.charAt(ix);
     if ('0' <= c && c <= '9') {
         scs[p] = scs[p].add(BigInteger.valueOf((int)(c - '0')));
     }
     else {
         char op = c;
         while (!('0' <= c && c <= '9')) {
             ix++;
             if (ix == a.length()) return ix;
             c = a.charAt(ix);
         }
         if (op == 'X') scs[p] = scs[p].multiply(BigInteger.valueOf((int)(c - '0')));
         if (op == 'D') scs[p] = scs[p].divide(BigInteger.valueOf((int)(c - '0')));
         if (op == 'S') scs[p] = scs[p].subtract(BigInteger.valueOf((int)(c - '0')));
     }
     return ix + 1;
 }
Ejemplo n.º 18
0
  public static void main(String[] args) throws IOException {
    Scanner scanner = new Scanner(new BufferedInputStream(System.in));
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    while (scanner.hasNextInt()) {
      int n = scanner.nextInt();
      int k = scanner.nextInt();

      BigInteger sum = BigInteger.ONE;

      for (int i = n; i > n - k; i--) {
        sum = sum.multiply(BigInteger.valueOf(i));
      }
      for (int i = 2; i <= k; i++) {
        sum = sum.divide(BigInteger.valueOf(i));
      }

      System.out.println(sum.toString().length());
    }
  }
Ejemplo n.º 19
0
  void start() throws IOException {
    BigInteger n = new BigInteger(reader.next());
    String s = reader.next();

    BigInteger answer = BigInteger.ONE;
    while (n.compareTo(BigInteger.ONE) > 0) {
      answer = answer.multiply(n);
      n = n.subtract(BigInteger.valueOf(s.length()));
    }
    writer.println(answer);
  }
Ejemplo n.º 20
0
 @Override
 public final XMLGregorianCalendar toJava() {
   return DF.newXMLGregorianCalendar(
       yea == Long.MAX_VALUE ? null : BigInteger.valueOf(yea > 0 ? yea : yea - 1),
       mon >= 0 ? mon + 1 : Integer.MIN_VALUE,
       day >= 0 ? day + 1 : Integer.MIN_VALUE,
       hou >= 0 ? hou : Integer.MIN_VALUE,
       min >= 0 ? min : Integer.MIN_VALUE,
       sec != null ? sec.intValue() : Integer.MIN_VALUE,
       sec != null ? sec.remainder(BigDecimal.ONE) : null,
       tz == Short.MAX_VALUE ? Integer.MIN_VALUE : tz);
 }
Ejemplo n.º 21
0
  public static void main(String[] args) {
    // Generics, varargs & boxing working together:
    List<Integer> li = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
    Integer result = reduce(li, new IntegerAdder());
    print(result);

    result = reduce(li, new IntegerSubtracter());
    print(result);

    print(filter(li, new GreaterThan<Integer>(4)));

    print(forEach(li, new MultiplyingIntegerCollector()).result());

    print(
        forEach(filter(li, new GreaterThan<Integer>(4)), new MultiplyingIntegerCollector())
            .result());

    MathContext mc = new MathContext(7);
    List<BigDecimal> lbd =
        Arrays.asList(
            new BigDecimal(1.1, mc),
            new BigDecimal(2.2, mc),
            new BigDecimal(3.3, mc),
            new BigDecimal(4.4, mc));
    BigDecimal rbd = reduce(lbd, new BigDecimalAdder());
    print(rbd);

    print(filter(lbd, new GreaterThan<BigDecimal>(new BigDecimal(3))));

    // Use the prime-generation facility of BigInteger:
    List<BigInteger> lbi = new ArrayList<BigInteger>();
    BigInteger bi = BigInteger.valueOf(11);
    for (int i = 0; i < 11; i++) {
      lbi.add(bi);
      bi = bi.nextProbablePrime();
    }
    print(lbi);

    BigInteger rbi = reduce(lbi, new BigIntegerAdder());
    print(rbi);
    // The sum of this list of primes is also prime:
    print(rbi.isProbablePrime(5));

    List<AtomicLong> lal =
        Arrays.asList(
            new AtomicLong(11), new AtomicLong(47), new AtomicLong(74), new AtomicLong(133));
    AtomicLong ral = reduce(lal, new AtomicLongAdder());
    print(ral);

    print(transform(lbd, new BigDecimalUlp()));
  }
Ejemplo n.º 22
0
  public static void main(String[] args) {
    BigInteger a = BigInteger.valueOf(1), // without OO
        b = 2, // with OO
        c1 = a.negate().add(b.multiply(b)).add(b.divide(a)), // without OO
        c2 = -a + b * b + b / a; // with OO

    if (c1.compareTo(c2) < 0 || c1.compareTo(c2) > 0)
      System.out.println("impossible"); // without OO
    if (c1 < c2 || c1 > c2) System.out.println("impossible"); // with OO

    HashMap<String, String> map = new HashMap<>();
    if (!map.containsKey("qwe")) map.put("qwe", "asd"); // without OO
    if (map["qwe"] == null) map["qwe"] = "asd"; // with OO
  }
Ejemplo n.º 23
0
 public static void abcd(String str) {
   BigInteger sum = BigInteger.ZERO;
   StringBuffer n = new StringBuffer("");
   for (int i = 0; i < str.length(); i++) {
     BigInteger ab = BigInteger.valueOf(((int) str.charAt(i)) - 96);
     sum = sum.add(div.pow(str.length() - i - 1).multiply(ab));
   }
   String s = sum.toString();
   for (int i = 0; i < s.length(); i++) {
     if (i % 3 == 0 && i != 0) n.insert(0, ",");
     n.insert(0, s.charAt(s.length() - i - 1));
   }
   while (str.length() < 22) str = str + " ";
   System.out.println(str + "" + n);
 }
Ejemplo n.º 24
0
 /** Test probable primes in the sieve and return successful candidates. */
 BigInteger retrieve(BigInteger initValue, int certainty, java.util.Random random) {
   // Examine the sieve one long at a time to find possible primes
   int offset = 1;
   for (int i = 0; i < bits.length; i++) {
     long nextLong = ~bits[i];
     for (int j = 0; j < 64; j++) {
       if ((nextLong & 1) == 1) {
         BigInteger candidate = initValue.add(BigInteger.valueOf(offset));
         if (candidate.primeToCertainty(certainty, random)) return candidate;
       }
       nextLong >>>= 1;
       offset += 2;
     }
   }
   return null;
 }
Ejemplo n.º 25
0
  public static void main(String[] args) throws IOException {
    Scanner scanner = new Scanner(new BufferedInputStream(System.in));
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    int n = 1;
    while (scanner.hasNextInt()) {
      int a = scanner.nextInt();
      int b = scanner.nextInt();
      if (a == 0) break;
      BigInteger sum = BigInteger.ZERO;
      BigInteger bb = BigInteger.valueOf(b);
      for (int i = 0; i < a; i++) sum = sum.add(scanner.nextBigInteger());

      System.out.println(
          "Bill #" + n + " costs " + sum + ": each friend should pay " + sum.divide(bb) + "\n");
      n++;
    }
  }
Ejemplo n.º 26
0
 public void DP() {
   for (int i = 0; i <= m; i++) {
     for (int j = 0; j <= sz; j++) {
       dp[i][j] = BigInteger.ZERO;
     }
   }
   dp[0][0] = BigInteger.ONE;
   for (int i = 0; i < m; i++) {
     for (int j = 0; j < sz; j++)
       if (dp[i][j].compareTo(BigInteger.valueOf(0)) == 1) {
         for (int k = 0; k < CD; k++) {
           if (flag[ch[j][k]] > 0 || flag[j] > 0) continue;
           dp[i + 1][ch[j][k]] = dp[i + 1][ch[j][k]].add(dp[i][j]);
         }
       }
   }
   ans = BigInteger.ZERO;
   for (int i = 0; i < sz; i++) ans = ans.add(dp[m][i]);
   out.println(ans);
 }
Ejemplo n.º 27
0
Archivo: vans.java Proyecto: were/progs
 void run() {
   int N = input.nextInt();
   f = new BigInteger[max(N + 1, 5)];
   f[1] = BigInteger.ZERO;
   f[2] = BigInteger.valueOf(2);
   f[3] = BigInteger.valueOf(4);
   g = new BigInteger[max(N + 1, 5)];
   g[1] = BigInteger.valueOf(2);
   g[2] = BigInteger.valueOf(2);
   g[3] = BigInteger.valueOf(8);
   for (int i = 4; i <= N; ++i) {
     g[i] =
         f[i - 1].multiply(BigInteger.valueOf(2)).add(g[i - 1]).add(g[i - 2]).subtract(g[i - 3]);
     f[i] = f[i - 1].add(g[i - 1]);
   }
   System.out.println(f[N]);
 }
Ejemplo n.º 28
0
/**
 * Utility functions for working with numbers This class is JDK 1.4 compatible.
 *
 * @author angel
 * @version $Id$
 * @since Jan 9, 2006
 */
public class NumberUtil {
  // ~ Static fields/initializers ---------------------------------------------

  private static final DecimalFormat floatFormatter;
  private static final DecimalFormat doubleFormatter;
  private static final BigInteger[] bigIntTenPow;
  private static final BigInteger[] bigIntMinUnscaled;
  private static final BigInteger[] bigIntMaxUnscaled;

  // For JDK 1.4 compatibility
  private static final BigInteger bigIntTen = BigInteger.valueOf(10);

  public static final Byte MIN_BYTE = new Byte(Byte.MIN_VALUE);
  public static final Byte MAX_BYTE = new Byte(Byte.MAX_VALUE);
  public static final Integer MIN_INTEGER = new Integer(Integer.MIN_VALUE);
  public static final Integer MAX_INTEGER = new Integer(Integer.MAX_VALUE);
  public static final Short MIN_SHORT = new Short(Short.MIN_VALUE);
  public static final Short MAX_SHORT = new Short(Short.MAX_VALUE);
  public static final Long MIN_LONG = new Long(Long.MIN_VALUE);
  public static final Long MAX_LONG = new Long(Long.MAX_VALUE);
  public static final Float MIN_FLOAT = new Float(-Float.MAX_VALUE);
  public static final Float MAX_FLOAT = new Float(Float.MAX_VALUE);
  public static final Double MIN_DOUBLE = new Double(-Double.MAX_VALUE);
  public static final Double MAX_DOUBLE = new Double(Double.MAX_VALUE);

  public static final Integer INTEGER_ZERO = new Integer(0);
  public static final Integer INTEGER_ONE = new Integer(1);

  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);
      }
    }
  }

  // ~ Methods ----------------------------------------------------------------

  public static final BigInteger powTen(int exponent) {
    if ((exponent >= 0) && (exponent < bigIntTenPow.length)) {
      return bigIntTenPow[exponent];
    } else {
      return bigIntTen.pow(exponent);
    }
  }

  public static final BigInteger getMaxUnscaled(int precision) {
    return bigIntMaxUnscaled[precision];
  }

  public static final BigInteger getMinUnscaled(int precision) {
    return bigIntMinUnscaled[precision];
  }

  public static final BigDecimal rescaleBigDecimal(BigDecimal bd, int scale) {
    if (bd != null) {
      bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
    }
    return bd;
  }

  public static final BigDecimal toBigDecimal(Number number, int scale) {
    BigDecimal bd = toBigDecimal(number);
    return rescaleBigDecimal(bd, scale);
  }

  public static final BigDecimal toBigDecimal(Number number) {
    if (number == null) {
      return null;
    }
    if (number instanceof BigDecimal) {
      return (BigDecimal) number;
    } else if ((number instanceof Double) || (number instanceof Float)) {
      // For JDK 1.4 compatibility
      return new BigDecimal(((Number) number).doubleValue());
      // return BigDecimal.valueOf(((Number) number).doubleValue());
    } else if (number instanceof BigInteger) {
      return new BigDecimal((BigInteger) number);
    } else {
      return new BigDecimal(((Number) number).longValue());
    }
  }

  /**
   * @return whether a BigDecimal is a valid Farrago decimal. If a BigDecimal's unscaled value
   *     overflows a long, then it is not a valid Farrago decimal.
   */
  public static boolean isValidDecimal(BigDecimal bd) {
    BigInteger usv = bd.unscaledValue();
    long usvl = usv.longValue();
    return usv.equals(BigInteger.valueOf(usvl));
  }

  public static NumberFormat getApproxFormatter(boolean isFloat) {
    return (isFloat) ? floatFormatter : doubleFormatter;
  }

  public static long round(double d) {
    if (d < 0) {
      return (long) (d - 0.5);
    } else {
      return (long) (d + 0.5);
    }
  }

  public static Double add(Double a, Double b) {
    if ((a == null) || (b == null)) {
      return null;
    }

    // For JDK 1.4 compatibility
    return new Double(a.doubleValue() + b.doubleValue());
    // return Double.valueOf(a.doubleValue() + b.doubleValue());
  }

  public static Double divide(Double a, Double b) {
    if ((a == null) || (b == null) || (b.doubleValue() == 0.0)) {
      return null;
    }

    // For JDK 1.4 compatibility
    return new Double(a.doubleValue() / b.doubleValue());
    // return Double.valueOf(a.doubleValue() / b.doubleValue());
  }

  public static Double multiply(Double a, Double b) {
    if ((a == null) || (b == null)) {
      return null;
    }

    // For JDK 1.4 compatibility
    return new Double(a.doubleValue() * b.doubleValue());
    // return Double.valueOf(a.doubleValue() * b.doubleValue());
  }
}
Ejemplo n.º 29
0
 /**
  * @return whether a BigDecimal is a valid Farrago decimal. If a BigDecimal's unscaled value
  *     overflows a long, then it is not a valid Farrago decimal.
  */
 public static boolean isValidDecimal(BigDecimal bd) {
   BigInteger usv = bd.unscaledValue();
   long usvl = usv.longValue();
   return usv.equals(BigInteger.valueOf(usvl));
 }
  public void testDeepLink() {
    Session ssn = SessionManager.getSession();

    DataObject[] users = new DataObject[4];

    DataObject group = getSession().create(getModelName() + ".Group");
    group.set("id", BigInteger.valueOf(users.length));
    group.set("email", "*****@*****.**");
    group.set("name", "SIPB");
    group.save();
    DataAssociation members = (DataAssociation) group.get("members");

    for (int i = 0; i < users.length; i++) {
      users[i] = ssn.create(getModelName() + ".User");
      users[i].set("id", BigInteger.valueOf(i));
      users[i].set("email", "*****@*****.**");
      users[i].set("firstName", "foo");
      users[i].set("lastNames", "bar");
      users[i].save();
      members.add(users[i]);
    }
    group.save();

    DataObject[] images = new DataObject[users.length / 2];
    for (int i = 0; i < images.length; i++) {
      images[i] = ssn.create(getModelName() + ".Image");
      images[i].set("id", BigInteger.valueOf(i));
      byte[] bytes = "This is the image.".getBytes();
      images[i].set("bytes", bytes);
      images[i].save();
    }

    // create link between user i and image i/2 with caption i
    for (int i = 0; i < users.length; i++) {
      // set image
      DataAssociation imageUsers = (DataAssociation) images[i / 2].get("users");
      DataObject link = imageUsers.add(users[i]);
      link.set("caption", String.valueOf(i));
      link.save();
    }

    DataCollection dc = ssn.retrieve(getModelName() + ".Group");
    dc.addEqualsFilter("members.image.link.caption", "0");
    assertEquals(1, dc.size());

    dc = ssn.retrieve(getModelName() + ".User");
    dc.addPath("image.link.caption");
    assertEquals(users.length, dc.size());
    while (dc.next()) {
      assertEquals(dc.get("id").toString(), dc.get("image.link.caption"));
    }

    dc = ssn.retrieve(getModelName() + ".User");
    dc.addPath("image.id");
    assertEquals(users.length, dc.size());
    while (dc.next()) {
      int id = ((BigInteger) dc.get("id")).intValue();
      assertEquals(BigInteger.valueOf(id / 2), dc.get("image.id"));
    }

    DataCollection dcUp = ssn.retrieve(getModelName() + ".User");
    DataCollection dcDown = ssn.retrieve(getModelName() + ".User");
    dcUp.addOrder("image.link.caption asc");
    dcDown.addOrder("image.link.caption desc");
    dcUp.next();
    dcDown.next();
    assertEquals(BigInteger.valueOf(0), dcUp.get("id"));
    assertEquals(BigInteger.valueOf(users.length - 1), dcDown.get("id"));
    dcUp.close();
    dcDown.close();

    dcUp = ssn.retrieve(getModelName() + ".Image");
    dcDown = ssn.retrieve(getModelName() + ".Image");
    dcUp.addOrder("users.link.caption asc");
    dcDown.addOrder("users.link.caption desc");
    dcUp.next();
    dcDown.next();
    assertEquals(BigInteger.valueOf(0), dcUp.get("id"));
    assertEquals(BigInteger.valueOf(images.length - 1), dcDown.get("id"));
    dcUp.close();
    dcDown.close();

    dc = ssn.retrieve(getModelName() + ".Group");
    dc.addFilter("members.image.id = 0");
    assertEquals(2, dc.size());

    dc = ssn.retrieve(getModelName() + ".Image");
    dc.addFilter("users.id = 0 and users.link.caption = '1'");
    assertEquals(0, dc.size());

    dc = ssn.retrieve(getModelName() + ".Group");
    dc.addPath("members.id");
    dc.addFilter("members.image.id = 0 and members.image.link.caption = '1'");
    assertTrue(dc.next());
    assertEquals(BigInteger.valueOf(1), dc.get("members.id"));
    assertFalse(dc.next());
  }