Created
August 2, 2010 12:46
-
-
Save 7shi/504588 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
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