Skip to content

Instantly share code, notes, and snippets.

@beyondlimits
Created July 21, 2019 13:13
Show Gist options
  • Save beyondlimits/a3dfe5f06be6263b389abfcc8aa3c46e to your computer and use it in GitHub Desktop.
Save beyondlimits/a3dfe5f06be6263b389abfcc8aa3c46e to your computer and use it in GitHub Desktop.
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
static unsigned short lookup_table[512];
unsigned short mul(unsigned char a, unsigned char b)
{
unsigned short x = a + b, y = (a > b) ? (a - b) : (b - a);
return lookup_table[x] - lookup_table[y];
}
void initialize()
{
int i;
for (i = 0; i < 512; ++i) {
// value ends with binary 00 (even) or 01 (odd)
// so we can cut it off.
lookup_table[i] = (i * i) >> 2;
}
}
int test()
{
int exit_code = EXIT_SUCCESS;
int a, b;
for (a = 0; a < 256; ++a) {
for (b = 0; b < 256; ++b) {
unsigned short expected = a * b, got = mul(a, b);
if (expected != got) {
warnx("mul(%d, %d) produces incorrect value. Expected: %d, got %d.", a, b, expected, got);
exit_code = EXIT_FAILURE;
}
}
}
return exit_code;
}
int main()
{
initialize();
int exit_code = test();
exit(exit_code);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment