Skip to content

Instantly share code, notes, and snippets.

@7shi
Created August 2, 2010 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 7shi/504588 to your computer and use it in GitHub Desktop.
Save 7shi/504588 to your computer and use it in GitHub Desktop.
using System;
class Division
{
static void Main(string[] args)
{
var r = new Random();
for (int i = 0; i < 10; i++)
{
int a = r.Next(), b = r.Next() & 0xffff;
Console.WriteLine("{0} / {1} = {2} ({3})", a, b, a / b, Div(a, b));
}
}
static int Div(int a, int b)
{
if (b == 0) throw new DivideByZeroException();
uint aa = (uint)Math.Abs(a), ab = (uint)Math.Abs(b);
if (aa < ab) return 0;
int sa = Math.Sign(a), sb = Math.Sign(b);
uint ret = 0, v = 1, aa2 = aa, ab2 = ab;
for (; aa > ab2; ab2 <<= 1, v <<= 1) ;
for (; ; )
{
ab2 >>= 1;
v >>= 1;
if (v == 0) break;
if (aa2 >= ab2)
{
ret += v;
aa2 -= ab2;
}
}
return sa == sb ? (int)ret : -(int)ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment