Path: utzoo!attcan!utgpu!news-server.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!cs.utexas.edu!wuarchive!julius.cs.uiuc.edu!apple!snorkelwacker!bloom-beacon!eru!hagbard!sunic!dkuug!freja.diku.dk!njk From: njk@diku.dk (Niels J|rgen Kruse) Newsgroups: comp.lang.c Subject: Re: random() error in Turbo C++ Message-ID: <1990Sep8.201520.15916@diku.dk> Date: 8 Sep 90 20:15:20 GMT References: <118662@linus.mitre.org> <17607@haddock.ima.isc.com> Organization: Department Of Computer Science, University Of Copenhagen Lines: 24 karl@haddock.ima.isc.com (Karl Heuer) writes: > If it's important, here is a correct algorithm. > #include > int random(int n) { > register int r; > do r = rand() / ((RAND_MAX + 1UL) / n); while (r >= n); > return (r); > } This require 2 divisions however. Here is an algorithm, that only require one division: #include int random (int n) { register int res, sor; do { res = (sor = rand()) % n; sor = RAND_MAX - (sor - res); } while (sor < n-1); return res; } No conversions either, it's all plain integer arithmetic. -- Niels J|rgen Kruse DIKU Graduate njk@diku.dk