Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

57
LINES

< > BotCompany Repo | #1002052 // Rat class (rational numbers based on BigInteger)

JavaX fragment (include)

1  
static class Rat {
2  
  BigInteger a, b;
3  
  
4  
  *() {} // for persistence
5  
  *(BigInteger *a, BigInteger *b) { simplify(); }
6  
  *(BigInteger *a, BigInteger *b, bool simplify) {
7  
    if (simplify) simplify();
8  
  }
9  
  *(BigInteger *a) { b = bigint(1); }
10  
  *(long a) { this(bigint(a)); }
11  
  *(long a, long b) { this(bigint(a), bigint(b)); }
12  
  
13  
  Rat multiply(BigInteger i) { ret multiply(new Rat(i)); }
14  
  Rat divide(BigInteger i) { ret divide(new Rat(i)); }
15  
  
16  
  Rat multiply(Rat r) {
17  
    ret new Rat(a.multiply(r.a), b.multiply(r.b));
18  
  }
19  
  
20  
  Rat divide(Rat r) {
21  
    ret new Rat(a.multiply(r.b), b.multiply(r.a));
22  
  }
23  
  
24  
  void simplify() {
25  
    // TODO: does this work for negative fractions (especially negative b)?
26  
    BigInteger gcd = a.gcd(b);
27  
    if (!eq(gcd, 1)) {
28  
      a = a.divide(gcd);
29  
      b = b.divide(gcd);
30  
    }
31  
  }
32  
  
33  
  public S toString() {
34  
    if (eq(b, 1))
35  
      ret a.toString();
36  
    else
37  
      ret a + "/" + b;
38  
  }
39  
  
40  
  // toString, return as mixed number if applicable
41  
  // todo: negatives
42  
  public S mixed() {
43  
    if (a.compareTo(b) > 0 && neq(b, 1)) {
44  
      BigInteger rest = a.mod(b);
45  
      BigInteger whole = a.divide(b);
46  
      ret whole + "+" + rest + "/" + b;
47  
    }
48  
    ret toString();
49  
  }
50  
  
51  
  // TODO (maybe): compare with int etc.
52  
  public boolean equals(O o) {
53  
    if (!(o instanceof Rat)) ret false;
54  
    Rat r = cast o;
55  
    ret eq(a, r.a) && eq(b, r.b);
56  
  }
57  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1002052
Snippet name: Rat class (rational numbers based on BigInteger)
Eternal ID of this version: #1002052/2
Text MD5: f0566aadbd36fbb1911a895c2761fd8c
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-01-08 01:56:41
Source code size: 1436 bytes / 57 lines
Pitched / IR pitched: No / No
Views / Downloads: 656 / 1598
Version history: 1 change(s)
Referenced in: [show references]