Skip to content

Instantly share code, notes, and snippets.

@7shi
Created August 7, 2010 18:16
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/513045 to your computer and use it in GitHub Desktop.
Save 7shi/513045 to your computer and use it in GitHub Desktop.
open System
let crcmod (a:int) (b:int) =
if b = 0 then raise (new DivideByZeroException())
let aa, ab = uint32(Math.Abs(a)), uint32(Math.Abs(b))
if aa < ab then 0 else
let shiftToTop v =
let rec stt v n =
if (v &&& 0x80000000u) <> 0u then n else stt (v <<< 1) (n + 1)
stt v 0
let s1, s2 = shiftToTop aa, shiftToTop ab
let ab2, v = ab <<< (s2 - s1), 1u <<< (31 - s1)
let rec mod' aa ab2 v =
let aa = if (aa &&& v) <> 0u then aa ^^^ ab2 else aa
if ab = ab2 then int(aa) else mod' aa (ab2 >>> 1) (v >>> 1)
let aret = mod' aa ab2 v
if Math.Sign(a) = Math.Sign(b) then aret else -aret
let r = new Random()
for i = 1 to 10 do
let a, b = r.Next(), r.Next() &&& 0xffff
printfn "%d / %d = %d ... %d(%d)" a b (a / b) (a % b) (crcmod a b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment