summaryrefslogtreecommitdiff
path: root/Source/Basetypes/BigNum.ssc
blob: b8ebcde0d40ae2440744cde16521726617efce2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
//-----------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation.  All Rights Reserved.
//
//-----------------------------------------------------------------------------
using System;
using System.Text;


namespace Microsoft.Basetypes {
  using Microsoft.Contracts;
  using BIM = System.Numerics.BigInteger;
  
  /// <summary>
  /// A thin wrapper around System.Numerics.BigInteger
  /// (to be able to define equality, etc. properly)
  /// </summary>
  public struct BigNum {
    
    // the internal representation
    [Rep] internal readonly System.Numerics.BigInteger val;
    public static readonly BigNum ZERO = new BigNum (BIM.Zero);
    public static readonly BigNum ONE  = new BigNum (BIM.One);
    public static readonly BigNum MINUS_ONE = new BigNum (-BIM.One);

    [Pure]
    public static BigNum FromInt(int v) {
      return new BigNum(new BIM(v));
    }

    [Pure]
    public static BigNum FromUInt(uint v) {
      return new BigNum(new BIM((long)v));
    }

    [Pure]
    public static BigNum FromLong(long v) {
      return new BigNum(new BIM(v));
    }

    [Pure]
    public static BigNum FromBigInt(System.Numerics.BigInteger v) {
      return new BigNum(v);
    }

    [Pure]
    public static BigNum FromULong(ulong v) {
      return FromString("" + v);
    }

    [Pure]
    public static BigNum FromString(string v) {
      try {
        return new BigNum(BIM.Parse(v));
      } catch (System.ArgumentException) {
        throw new FormatException();
      }
    }

    public static bool TryParse(string v, out BigNum res) {
      try {
	    res = BigNum.FromString(v);
        return true;
	  } catch (FormatException) {
	    res = ZERO;
	    return false;
      }
    }

    // Convert to int, without checking whether overflows occur
    public int ToInt {
      get {
        return (int)val;
      }
    }

    // Convert to int; assert that no overflows occur
    public int ToIntSafe {
      get {
        assert this.InInt32;
        return this.ToInt;
      }
    }

    public Rational ToRational {
      get {
        return new Rational (this, BigNum.ONE);
      }
	}

    internal BigNum(System.Numerics.BigInteger val) {
      this.val = val;
    }
    
    public static bool operator==(BigNum x, BigNum y) {
      return (x.val == y.val);
    }

    public static bool operator!=(BigNum x, BigNum y) {
      return !(x.val == y.val);
    }

    [Pure][Reads(ReadsAttribute.Reads.Nothing)]
    public override bool Equals(object obj) {
      if (obj == null) return false;
      if (!(obj is BigNum)) return false;
      
      BigNum other = (BigNum)obj;
      return (this.val == other.val);
    }
    
    [Pure]
    public override int GetHashCode() {
      return this.val.GetHashCode();
    }
    
    [Pure]
    public override string! ToString() {
      return (!)val.ToString();
    }

    //////////////////////////////////////////////////////////////////////////////
    // Very limited support for format strings
    // Note: Negative integers are linearised with a minus "-" in hexadecimal,
    // not in 2-complement notation (in contrast to what the method
    // int32.ToString(format) does) 

    [Pure]
	public string! ToString(string! format) {
        if (format.StartsWith("d") || format.StartsWith("D")) {
            string! res = this.Abs.ToString();
			return addMinus(this.Signum,
                            prefixWithZeros(extractPrecision(format), res));
        } else if (format.StartsWith("x") || format.StartsWith("X")) {
            string! res = this.toHex(format.Substring(0, 1));
			return addMinus(this.Signum,
                            prefixWithZeros(extractPrecision(format), res));
        } else {
			throw new FormatException("Format " + format + " is not supported");
        }
	}

    private static readonly System.Numerics.BigInteger BI_2_TO_24 = new BIM(0x1000000);    

    [Pure]
    private string! toHex(string! format) {
	    string! res = "";
        System.Numerics.BigInteger rem = this.Abs.val;

        while (rem > BIM.Zero) {
          res = ((int)(rem %BI_2_TO_24)).ToString(format) + res;
          rem = rem / BI_2_TO_24;
        }

        return res;
    }

    [Pure]
    private int extractPrecision(string! format) {
        if (format.Length > 1)
          // will throw a FormatException if the precision is invalid;
          // that is ok
          return Int32.Parse(format.Substring(1));
        // always output at least one digit
        return 1;
    }

    [Pure]
    private string! addMinus(int signum, string! suffix) {
        if (signum < 0)
          return "-" + suffix;
        return suffix;
    }

    [Pure]
    private string! prefixWithZeros(int minLength, string! suffix) {
        StringBuilder res = new StringBuilder();
        while (res.Length + suffix.Length < minLength)
          res.Append("0");
        res.Append(suffix);
        return res.ToString();
    }

    ////////////////////////////////////////////////////////////////////////////
    // Basic arithmetic operations
    
    public BigNum Abs {
      get {
        return new BigNum(BIM.Abs(this.val));
      }
    }

    public BigNum Neg {
      get {
        return new BigNum(-this.val);
      }
    }

    [Pure]
    public static BigNum operator-(BigNum x) {
      return x.Neg;
    }

    [Pure]
    public static BigNum operator+(BigNum x, BigNum y) {
      return new BigNum(x.val + y.val);
    }

    [Pure]
    public static BigNum operator-(BigNum x, BigNum y) {
      return new BigNum(x.val - y.val);
    }

    [Pure]
    public static BigNum operator*(BigNum x, BigNum y) {
      return new BigNum(x.val * y.val);
    }

    // TODO: check that this has a proper semantics (which? :-))
    [Pure]
    public static BigNum operator/(BigNum x, BigNum y) {
      return new BigNum(x.val / y.val);
    }

    // TODO: check that this has a proper semantics (which? :-))
    [Pure]
    public static BigNum operator%(BigNum x, BigNum y) {
      return new BigNum(x.val - ((x.val / y.val) * y.val));
    }

    [Pure]
    public BigNum Min(BigNum that) {
      return new BigNum(this.val <= that.val ? this.val : that.val);
    }

    [Pure]
    public BigNum Max(BigNum that) {
      return new BigNum(this.val >= that.val ? this.val : that.val);
    }

    /// <summary>
    /// Returns the greatest common divisor of this and _y.
    /// </summary>
    /// <param name="_y"></param>
    /// <returns></returns>
    public BigNum Gcd(BigNum _y)
        ensures !result.IsNegative;
    {
      BigNum x = this.Abs;
      BigNum y = _y.Abs;

      while (true)
      {
        if (x < y)
        {
          y = y % x;
          if (y.IsZero)
          {
            return x;
          }
        }
        else
        {
          x = x % y;
          if (x.IsZero)
          {
            return y;
          }
        }
      }
      return ZERO; // make compiler shut up
    }

    ////////////////////////////////////////////////////////////////////////////
    // Some basic comparison operations

    public int Signum {
	  get {
		return this.val.Sign;
	  }
    }

    public bool IsPositive {
      get {
        return (this.val > BIM.Zero);
      }
    }

    public bool IsNegative {
      get {
        return (this.val < BIM.Zero);
      }
    }

    public bool IsZero {
      get {
        return this.val.IsZero;
      }
    }

    [Pure]
    public int CompareTo(BigNum that) {
	  if (this.val == that.val) return 0;
	  if (this.val < that.val) return -1;
	  return 1;
    }

    [Pure]
    public static bool operator<(BigNum x, BigNum y) {
      return (x.val < y.val);
    }

    [Pure]
    public static bool operator>(BigNum x, BigNum y) {
      return (x.val > y.val);
    }

    [Pure]
    public static bool operator<=(BigNum x, BigNum y) {
      return (x.val <= y.val);
    }

    [Pure]
    public static bool operator>=(BigNum x, BigNum y) {
      return (x.val >= y.val);
    }

    
    private static readonly System.Numerics.BigInteger MaxInt32 =
      new BIM(Int32.MaxValue);
    private static readonly System.Numerics.BigInteger MinInt32 =
      new BIM(Int32.MinValue);
 
    public bool InInt32 {
      get {
        return (val >= MinInt32) && (val <= MaxInt32);
      }
    }
  }
}