Why does rand ()% 7 always return 0?

This seems to be a really weird problem:

This is my code:

#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { @autoreleasepool { srand((unsigned int)time(NULL)); int newRandomNumber = 0; newRandomNumber = rand() % 7; NSLog(@"%d", rand() % 7); //This prints out what I expected NSLog(@"newRandomNumber = %d", newRandomNumber); // This always prints out 0! } return 0; } 

If I replace one line that says

 newRandomNumber = rand() % 7 

from

 newRandomNumber = rand() % 8 

everything works perfectly. Why is this so?

+35
c random objective-c
Oct 23 2018-11-23T00:
source share
2 answers

Well it

 int seed; for(seed = 1; seed < 10; seed++) { srand(seed); printf("%4d %16d\n", seed, rand()); } 

prints

  1 16807 2 33614 3 50421 4 67228 5 84035 6 100842 7 117649 8 134456 9 151263 

which makes me think that rand() = seed * 16807

Wikipedia article Linear congruent generator confirms that CarbonLib does use Xn + 1 = Xn * 16807 to generate random numbers.

+36
Oct 23 '11 at 17:34
source share

It seems unlikely, but the execution of some tests, after srand, the first rand seems to always be divisible by 7, at least in an int-sized variable.

On several runs, I got 1303562743, 2119476443 and 2120232758, all of which are from 7 to 0.

The second rand() works because it is the second rand() . Throw rand() to your first rand() ... or better yet, use the best random or arc4rand random number arc4rand , if available.

Also see the stack overflow question. Why (rand ()% anything) is always 0 in C ++? .

+9
Oct 23 '11 at 15:41
source share



All Articles