Skip to content

Instantly share code, notes, and snippets.

@wallstop
Created April 23, 2014 01:19
Show Gist options
  • Save wallstop/11199882 to your computer and use it in GitHub Desktop.
Save wallstop/11199882 to your computer and use it in GitHub Desktop.
// sub, mul, and div using only the "+" operator...
int negate(int a)
{
int i = a < 0 ? 1 : -1;
int ret = 0;
for(; a != 0; a += i)
ret += i;
return ret;
}
int sub(int a, int b)
{
return a + negate(b);
}
int mul(int a, int b)
{
if(a == 0 || b == 0)
return 0;
b = a < 0 ? negate(b) : b;
a = a < 0 ? negate(a) : a;
int temp = 0;
for(; a != 0; a += -1)
temp += b;
return temp;
}
int div(int a, int b)
{
if(b == 0 || a == 0)
return 0;
int i = ((a < 0 && b < 0) || (a > 0) && (b > 0)) ? 1 : -1;
b = b < 0 ? negate(b) : b;
a = a < 0 ? negate(a) : a;
int counter = 0;
int ret = 0;
for(; a != 0; a += -1)
{
counter++;
if(counter == b)
{
ret += i;
counter = 0;
}
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment