001: package mlsub.typing.lowlevel;
002:
003: import java.math.BigInteger;
004:
005: /**
006: * @version $Revision: 1.1 $, $Date: 2000/06/14 13:32:54 $
007: * @author Alexandre Frey
008: */
009: public class Misc {
010: // not instantiable
011: private Misc() {
012: }
013:
014: public static String arrayToString(Object[] array, int n,
015: String lpar, String sep, String rpar) {
016: StringBuffer sb = new StringBuffer();
017: sb.append(lpar);
018: for (int i = 0; i < n; i++) {
019: if (i > 0) {
020: sb.append(sep);
021: }
022: sb.append(array[i]);
023: }
024: sb.append(rpar);
025: return sb.toString();
026: }
027:
028: public static String arrayToString(int[] array, int n, String lpar,
029: String sep, String rpar) {
030: StringBuffer sb = new StringBuffer();
031: sb.append(lpar);
032: for (int i = 0; i < n; i++) {
033: if (i > 0) {
034: sb.append(sep);
035: }
036: sb.append(array[i]);
037: }
038: sb.append(rpar);
039: return sb.toString();
040: }
041:
042: public static String arrayToString(Object[] array, String lpar,
043: String sep, String rpar) {
044: return arrayToString(array, array.length, lpar, sep, rpar);
045: }
046:
047: public static String arrayToString(int[] array, String lpar,
048: String sep, String rpar) {
049: return arrayToString(array, array.length, lpar, sep, rpar);
050: }
051:
052: public static void printStackTrace() {
053: try {
054: throw new Throwable();
055: } catch (Throwable e) {
056: e.printStackTrace();
057: }
058: }
059:
060: /**
061: * floor(n / d)
062: **/
063: public static BigInteger div(BigInteger n, BigInteger d)
064: throws ArithmeticException {
065: if (n.signum() == d.signum()) {
066: return n.divide(d);
067: } else {
068: BigInteger[] divrem = n.divideAndRemainder(d);
069: BigInteger div = divrem[0];
070: BigInteger rem = divrem[1];
071: if (rem.signum() == 0) {
072: return div;
073: } else {
074: return div.add(BigInteger.valueOf(-1));
075: }
076: }
077: }
078:
079: /**
080: * if d == -1, n must be != Integer.MIN_VALUE (otherwise, overflow would
081: * occur and give the incorrect result Integer.MIN_VALUE)
082: **/
083: public static int div(int n, int d) throws ArithmeticException {
084: if ((n >= 0 && d > 0) || (n <= 0 && d < 0)) {
085: return n / d;
086: } else {
087: int q = n / d;
088: int r = n % d;
089: if (r == 0) {
090: return q;
091: } else {
092: return q - 1;
093: }
094: }
095: }
096:
097: /**
098: * n - div(n, d) * d
099: **/
100: public static BigInteger mod(BigInteger n, BigInteger d)
101: throws ArithmeticException {
102: BigInteger rem = n.remainder(d);
103: if (rem.signum() == 0) {
104: return rem;
105: }
106: if (n.signum() == d.signum()) {
107: return rem;
108: } else {
109: return rem.add(d);
110: }
111: }
112:
113: public static int mod(int n, int d) throws ArithmeticException {
114: int r = n % d;
115: if (r == 0) {
116: return r;
117: } else if ((n >= 0 && d > 0) || (n <= 0 && d < 0)) {
118: return r;
119: } else {
120: return r + d;
121: }
122: }
123: }
|