Advertisement
Guest User

Untitled

a guest
Jan 19th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. // This file is part of www.nand2tetris.org
  2. // and the book "The Elements of Computing Systems"
  3. // by Nisan and Schocken, MIT Press.
  4. // File name: projects/09/Fraction/Fraction.jack
  5.  
  6. /** Represents the Fraction type and related operations. */
  7. class Fraction {
  8. field int numerator, denominator; // field = property = member variable.
  9.  
  10. /** Constructs a (reduced) fraction from the given numerator and denominator. */
  11. constructor Fraction new(int x, int y) {
  12. let numerator = x;
  13. let denominator = y;
  14. do reduce(); // reduces the fraction
  15. return this; // a constructor is expected to return a reference to the new object
  16. }
  17.  
  18. // Reduces this fraction.
  19. method void reduce() {
  20. var int g;
  21. let g = Fraction.gcd(numerator, denominator);
  22. if (g > 1) {
  23. let numerator = numerator / g;
  24. let denominator = denominator / g;
  25. }
  26. return;
  27. }
  28.  
  29. /** Accessors. */
  30. method int getNumerator() { return numerator; }
  31. method int getDenominator() { return denominator; }
  32.  
  33. /** Returns the sum of this fraction and the other one. */
  34. method Fraction plus(Fraction other) {
  35. var int sum;
  36. let sum = (numerator * other.getDenominator()) + (other.getNumerator() * denominator);
  37. return Fraction.new(sum, denominator * other.getDenominator());
  38. }
  39.  
  40. // More fraction-related methods (minus, times, div, etc.) can be added here.
  41.  
  42. /** Disposes this fraction. */
  43. method void dispose() {
  44. do Memory.deAlloc(this); // uses an OS routine to recycle the memory held by the object
  45. return;
  46. }
  47.  
  48. /** Prints this fraction in the format x/y. */
  49. method void print() {
  50. do Output.printInt(numerator);
  51. do Output.printString("/");
  52. do Output.printInt(denominator);
  53. return;
  54. }
  55.  
  56. // Computes the greatest common divisor of the given integers.
  57. function int gcd(int a, int b) {
  58. var int r;
  59. while (~(b = 0)) { // applies Euclid's algorithm
  60. let r = a - (b * (a / b)); // r = remainder of the integer division a/b
  61. let a = b; let b = r;
  62. }
  63. return a;
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement