/** * A library of commonly used mathematical functions. * Note: Jack compilers implement multiplication and division using OS method calls. */ class Math { static Array mask; /** Initializes the library. */ function void init() { var int temp, i; let mask = Array.new(16); let temp = 1; let i = 0; while(i < 16){ let mask[i] = temp; let temp = temp + temp; let i = i + 1; } return; } /** Returns the absolute value of x. */ function int abs(int x) { if(x < 0){ let x = -x; } return x; } /** Returns the product of x and y. * When a Jack compiler detects the multiplication operator '*' in the * program's code, it handles it by invoking this method. In other words, * the Jack expressions x*y and multiply(x,y) return the same value. */ function int multiply(int x, int y) { var boolean negative; var int sum, shiftedX, i; let negative = false; let sum = 0; let i = 0; if(x < 0){ let negative = true; } if(y < 0){ let negative = ~negative; } let x = Math.abs(x); let y = Math.abs(y); let shiftedX = x; while(i < 16){ if(~((mask[i] & y) = 0)){ let sum = sum + shiftedX; } let shiftedX = shiftedX + shiftedX; let i = i + 1; } if(negative){ let sum = -sum; } return sum; } /** Returns the integer part of n/d. * When a Jack compiler detects the multiplication operator '/' in the * program's code, it handles it by invoking this method. In other words, * the Jack expressions n/d and divide(n,d) return the same value. */ function int divide(int n, int d){ var int result, a, b; var boolean negative; if(d = 0){ do Sys.error(3); } let negative = false; if(n < 0){ let negative = true; } if(d < 0){ let negative = ~negative; } let n = Math.abs(n); let d = Math.abs(d); let result = 0; while(~(n < d)){ let a = d; let b = 1; while((a + a) < n){ let a = a + a; let b = b + b; } let result = result + b; let n = n - a; } if(negative){ let result = -result; } return result; } /** Returns the integer part of the square root of x. */ function int sqrt(int x) { var int i, y, temp; if(x < 0){ do Sys.error(4); } let i = 7; let y = 0; while(i > -1){ let temp = (y + mask[i]) * (y + mask[i]); if(((temp < x) | (temp = x)) & (temp > 0)){ let y = y + mask[i]; } let i = i - 1; } return y; } /** Returns the greater number. */ function int max(int a, int b) { if(a > b){ return a; } return b; } /** Returns the smaller number. */ function int min(int a, int b) { if(a < b){ return a; } return b; } }