|
1 | 1 | #include "test_framework/generic_test.h" |
| 2 | + |
| 3 | +void printBin(unsigned long long val, size_t len, const std::string& suffix) { |
| 4 | + std::string binval; |
| 5 | + for (size_t i = 0; i < len; i++) { |
| 6 | + binval.append(val & 1 ? "1" : "0"); |
| 7 | + val >>= 1; |
| 8 | + } |
| 9 | + reverse(binval.begin(), binval.end()); |
| 10 | + printf("%s (%s)\n", binval.c_str(), suffix.c_str()); |
| 11 | +} |
| 12 | + |
| 13 | +unsigned long long Add(unsigned long long a, unsigned long long b) { |
| 14 | + /* |
| 15 | + total = a^b |
| 16 | + carry = (a & b) << 1 |
| 17 | + while carry: |
| 18 | + newTotal = total ^ carry |
| 19 | + newCarry = (total & carry) << 1 |
| 20 | + total, carry = newTotal, newCarry |
| 21 | + return total |
| 22 | + */ |
| 23 | + unsigned long long total = a ^ b; |
| 24 | + unsigned long long carry = (a & b) << 1; |
| 25 | + while (carry) { |
| 26 | + unsigned long long newTotal = total ^ carry; |
| 27 | + carry = (total & carry) << 1; |
| 28 | + total = newTotal; |
| 29 | + } |
| 30 | + return total; |
| 31 | +} |
| 32 | + |
2 | 33 | unsigned long long Multiply(unsigned long long x, unsigned long long y) { |
3 | | - // TODO - you fill in here. |
4 | | - return 0; |
| 34 | + /* |
| 35 | + - Can only use assignment, comparisons, and bitwise operations (&, |, ~, ^) |
| 36 | + - Lshift is a multiply by 2 |
| 37 | + - Clearing the lowest bit and setting all to the right of it: subtract 1 |
| 38 | + - Adding: bitwise xor with carry |
| 39 | + (3+3=6) |
| 40 | + 11 + |
| 41 | + 11 = |
| 42 | + 110 |
| 43 | + - Multiply can be iterative addition, but without subtraction this will be |
| 44 | + hard |
| 45 | + - Multiply: prod = 0. Until b=0, if lowest bit is set, add prod+=a. Right |
| 46 | + shift b, leftshift a. (3*3=9) 11 * 11 = 1001 (5*5=25) 101 * 101 = 11001 |
| 47 | + */ |
| 48 | + unsigned long long prod = 0; |
| 49 | + while (y) { |
| 50 | + if (y & 1) { |
| 51 | + prod = Add(x, prod); |
| 52 | + } |
| 53 | + y >>= 1; |
| 54 | + x <<= 1; |
| 55 | + } |
| 56 | + |
| 57 | + return prod; |
5 | 58 | } |
6 | 59 |
|
7 | 60 | int main(int argc, char* argv[]) { |
|
0 commit comments