Created
July 21, 2019 13:13
-
-
Save beyondlimits/a3dfe5f06be6263b389abfcc8aa3c46e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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