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)

static class Rat {
  BigInteger a, b;
  
  *() {} // for persistence
  *(BigInteger *a, BigInteger *b) { simplify(); }
  *(BigInteger *a, BigInteger *b, bool simplify) {
    if (simplify) simplify();
  }
  *(BigInteger *a) { b = bigint(1); }
  *(long a) { this(bigint(a)); }
  *(long a, long b) { this(bigint(a), bigint(b)); }
  
  Rat multiply(BigInteger i) { ret multiply(new Rat(i)); }
  Rat divide(BigInteger i) { ret divide(new Rat(i)); }
  
  Rat multiply(Rat r) {
    ret new Rat(a.multiply(r.a), b.multiply(r.b));
  }
  
  Rat divide(Rat r) {
    ret new Rat(a.multiply(r.b), b.multiply(r.a));
  }
  
  void simplify() {
    // TODO: does this work for negative fractions (especially negative b)?
    BigInteger gcd = a.gcd(b);
    if (!eq(gcd, 1)) {
      a = a.divide(gcd);
      b = b.divide(gcd);
    }
  }
  
  public S toString() {
    if (eq(b, 1))
      ret a.toString();
    else
      ret a + "/" + b;
  }
  
  // toString, return as mixed number if applicable
  // todo: negatives
  public S mixed() {
    if (a.compareTo(b) > 0 && neq(b, 1)) {
      BigInteger rest = a.mod(b);
      BigInteger whole = a.divide(b);
      ret whole + "+" + rest + "/" + b;
    }
    ret toString();
  }
  
  // TODO (maybe): compare with int etc.
  public boolean equals(O o) {
    if (!(o instanceof Rat)) ret false;
    Rat r = cast o;
    ret eq(a, r.a) && eq(b, r.b);
  }
}

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: 742 / 1698
Version history: 1 change(s)
Referenced in: #1003872 - Integrating #759 in One Program
#1003874 - Backup of #759 Before Integration
#1004091 - 759 with new loadClasses (spike)
#1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)
#3000382 - Answer for ferdie (>> t = 1, f = 0)
#3000383 - Answer for funkoverflow (>> t=1, f=0 okay)