By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,101 Members | 1,340 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,101 IT Pros & Developers. It's quick & easy.

How to generate a random number

100+
P: 151
Hi,

i am generating random number 10000 times but i want outof 3400000 times, there should be 10000 times it should be zero. How can i implement this?

int i = 0;
while(i<3400000)
{
int r_number= rand() % 10000;
if(r_number == 0)
{
// do something
}
i++;
}

i need r_number should be zero 10000 times. I have tried but nothing seem to be working. Thanks in advance.
Nov 18 '10 #1
Share this Question
Share on Google+
2 Replies


100+
P: 1,059
it means Random are not returning number which is divisible by 10000. What is the range of random? what is your expecting range? I cant recall that either...
Nov 18 '10 #2

Banfa
Expert Mod 5K+
P: 8,916
No you are generating a random number 340000 times.

Look at your odds, you generate a random number X in the range 0 <= X < 10000. So the change it is 0 is 1/10000. If you are generating 340000 that means you can expect around 340000 * 1/10000 or 340000 / 10000 or 340 to be 0.

This is born out if you add just a little output to your program like this

Expand|Select|Wrap|Line Numbers
  1. #include "stdlib.h"
  2. #include "stdio.h"
  3. #include "time.h"
  4.  
  5. int main()
  6. {
  7.     int i = 0;
  8.     int zero = 0;
  9.  
  10.     srand(time(NULL));
  11.  
  12.     while(i<3400000)
  13.     {
  14.         int r_number= rand() % 10000;
  15.         if(r_number == 0)
  16.         {
  17.         // do something
  18.             printf("0 at %d\n", i);
  19.             zero++;
  20.         }
  21.  
  22.         i++;
  23.     }
  24.  
  25.     printf("Total 0: %d\n", zero);
  26.  
  27.     return 0;
  28. }
  29.  
If you want 10,000 0 then you need to either alter the the number of iterations of the while loop or you need to alter the probability of getting a zero by altering the range of the random numbers you are generating or you need to alter both such that

<NumberOfIterations> * <ProbabilityOf0> = 10000
Nov 18 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.