1. No Profile Picture
Junior Member
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2003
Posts
16
Rep Power
0

#### Newbie help

Can someone tell me how to create a random number generator that chooses 2 leap years between 1900 and 2000? I do not know where to even begin. Any help is appreciated. Thanks.

:confused:
2. Try using srand(), rand() and the % operator. You might want to read the man pages for rand() and srand() at http://www.openbsd.org/cgi-bin/man.c...86&format=html first. To get a leap year, the rules are:
1. Year should be divisible by 4
2. Centuries are excluded from rule 1, unless the century is divisible by 400.

From rules 1 and 2, we see that the 1904 is a leap year (obeys rules 1 and 2), 1900 is not (obeys 1 but not 2), 1976 is a leap year (obeys rules 1 and 2), 2000 is a leap year (obeys rules 1 and 2) etc. So now we can formulate an algorithm for generating leap years.

1. Pick a number randomly between 1 and 25.
2. Multiply this number by 4.

Now, if you read the documentation for the rand() function, you'll notice that it returns a # between 0 and RAND_MAX (which is a large number > 25). So, to get a number between 0 and 24, all you have to do is modulo divide by 25. Add 1 to this and you end up with a number between 1 and 25. So if you do this:
randnum = rand() % 25 + 1;
this will ensure that randnum is between 1 and 25.

With that said, your code could look something like this.
Code:
```#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
int randnum;

/* Seed random # generator with current time.
This may be a poor choice for crypto stuff,
but may do fine for the problem at hand.
Pick some other seed value if you like */
srand(time(NULL));
randnum = (rand() % 25 + 1) * 4 + 1900; /* Get random year */

printf("The year is %d\n", randnum);
return 0;
}```
Hope this helps :)
3. No Profile Picture
Junior Member
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2003
Posts
16
Rep Power
0
4. No Profile Picture
status unknown
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2003
Posts
262
Rep Power
15
Originally posted by cavecrazy