| 43 | /* Divide a by b by literally counting how many times b can go into |
| 44 | * a. That is, count how many times you can add b to itself until you reach a. */ |
| 45 | public static int divide(int a, int b) throws java.lang.ArithmeticException { |
| 46 | if (b == 0) { |
| 47 | throw new java.lang.ArithmeticException("ERROR: Divide by zero."); |
| 48 | } |
| 49 | int absa = abs(a); |
| 50 | int absb = abs(b); |
| 51 | |
| 52 | int product = 0; |
| 53 | int x = 0; |
| 54 | while (product + absb <= absa) { /* don't go past a */ |
| 55 | product += absb; |
| 56 | x++; |
| 57 | } |
| 58 | |
| 59 | if ((a < 0 && b < 0) || (a > 0 && b > 0)) { |
| 60 | return x; |
| 61 | } else { |
| 62 | return negate(x); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | public static int randomInt(int n) { |
| 67 | return (int) (Math.random() * n); |