www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/08/29/13:53:02

Xref: news2.mv.net comp.os.msdos.djgpp:8023
From: Erik Max Francis <max AT alcyone DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: random() and rand() question
Date: Thu, 29 Aug 1996 07:40:29 -0700
Organization: Alcyone Systems
Lines: 17
Message-ID: <3225ABDD.7AF48E03@alcyone.com>
References: <DwvF3A DOT H2r AT interactive DOT net>
NNTP-Posting-Host: newton.alcyone.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

J.J. Pierson wrote:

> Silly question... How would I go about getting a random number from say 1
> to a specified number?

For a number between 1 and n, use 

    rand()%n + 1.

If n is an even power of 2, then bitwise-anding a mask will be faste:

    rand()&(n - 1) + 1.

-- 
Erik Max Francis, &tSftDotIotE   http://www.alcyone.com/max/   max AT alcyone DOT com
San Jose, California   ICBM 37 20 07 N 121 53 38 W   R^4: the 4th R is respect
"Out from his breast/his soul went to seek/the doom of the just." -- _Beowulf_

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019