andy0130tw
9/3/2016 - 8:58 AM

Bitwise add / multiplying, revisiting functional programming (?

Bitwise add / multiplying, revisiting functional programming (?

#include<stdio.h>
#include<assert.h>

int add(int a, int b) {
    if (b == 0) return a;
    int sum = a ^ b;
    int carry = (a & b) << 1;
    return add(sum, carry);
}

int multiply(int a, int b) {
    if (!(a && b)) return 0;
    // optimize for recursion level
    if (a < b) return multiply(b, a);
    return (b & 1) ? add(a, multiply(a, b >> 1) << 1) : multiply(a, b >> 1) << 1;
}

int main() {
    for (int i = 1; i <= 9; i++) {
        for (int j = 1; j <= 9; j++) {
            assert(i + j == add(i, j));
            assert(i * j == multiply(i, j));
        }
    }
}